﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
//
using HRM.HRMServiceProxy;
using RateInfo = HRM.BusinessLogic.RateInfo;
using HeaderInfo = HRM.BusinessLogic.BhHeaderInfo;
using DetailInfo = HRM.BusinessLogic.BhDetailInfo;
using PositionInfo = HRM.HRMServiceProxy.PositionInfo;
using HRM.BusinessLogic;

namespace HRM
{
    public partial class frmInsurance : FormBase
    {
        bool isChange = false;


        DialogResult dlgResult = DialogResult.Cancel;
        RoleRightInfo _listRole;
        //
        HeaderInfo _HeaderInfo;
        DetailInfo _DetailInfo;
        DetailInfo _DetailInfoNew;
        EmployeeClient _wcfEmployee;
        EmployeeInfo _EmployeeInfo;
        RegionClient _wcfRegion;
        HospitalClient _wcfHospital;
        PositionClient _wcfPosition;
        PositionInfo _PositionInfo;
        RateInfo _RateInfo;
        BasicSalaryClient _wcfSalary;
        BasicSalaryInfo _BasicSalaryInfo;
        PositionDetailClient _wcfPositionDetal;
        PositionDetailInfo _PDInfo;
        PremiumClient _wcfPremium;
        PremiumInfo _PremiumInfo;
        InsTypeClient _wcfInsType;
        int _DocumentID = 0;
        int _DetailID = 0;
        int _EmployeeID = 0;
        string _Type = "";
        int[] arg_HeaderID = null;
        DateTime _ViewDate = DateTime.MinValue;
        public int _Approved = 0;
        bool _TakeCard = false;
        DateTime _fromDate = DateTime.MinValue;
        DateTime _toDate = DateTime.MinValue;
        DataTable dtQTBHXH = null;
        DataTable dtQTBHTN = null;
        DataTable dtQTBHTrongKy = null;
        Decimal Current_UnemployedRate = 0;
        DataTable dtInsTypeCode = null;

        private string lblDsPhatSinh = "";

        public frmInsurance() { }
        public frmInsurance(int DocumentID, RoleRightInfo listRole, DateTime ViewDate, string Type, int Approved)
        {
            InitializeComponent();
            //
            _HeaderInfo = new HeaderInfo();
            _DetailInfo = new DetailInfo();
            _wcfEmployee = Service.Employee();
            _EmployeeInfo = new EmployeeInfo();
            _wcfRegion = Service.Region();
            _wcfHospital = Service.Hospital();
            _wcfPositionDetal = Service.PositionDetail();
            _wcfPremium = Service.Premium();
            _wcfSalary = Service.BasicSalary();
            _wcfPosition = Service.Position();
            _PositionInfo = new PositionInfo();
            _wcfInsType = Service.InsType();
            int counter = 0;
            dtInsTypeCode = _wcfInsType.InsType_GetList(out counter, 0, 9999).Tables[0];
            //

            _DocumentID = DocumentID;
            _ViewDate = ViewDate;
            _Approved = Approved;
            _Type = Type;
            _listRole = listRole;
        }

        public override void Show_Form()
        {
            this.Show();
        }


        public void TextBox_SetTransparentLabel(Label lbl, TextBox txt)
        {
            var pos = this.PointToScreen(lbl.Location);
            pos = txt.PointToClient(pos);
            lbl.Parent = txt;
            lbl.Location = pos;
            lbl.Visible = true;
            lbl.Text = "%";
            lbl.BackColor = Color.Transparent;
            lbl.BorderStyle = BorderStyle.FixedSingle;
            //lbl.Invalidate();
            //txt.Invalidate();
        }

        //Khởi tạo giá trị cho các control
        protected override void Init_Control()
        {
            
            //----------------

            this.KeyPreview = true;
            lblDsPhatSinh = grbDSPhatSinh.Text;
            Control_HandlerValid(grbPhatSinh);
            Pager.AllowChangePageSize = false;
            //pagerToolStripItem1.CustomPageInfo = "Kỳ {0}/{1}";

            //Đặt dấu % hiển thị mờ dưới ô textbox
            //FormGlobals.TextBox_SetWaterMark("%", false, 2
            //    , txtDetail_Oldoverfactor_Percent
            //    , txtDetail_Oldjobfactor_Percent
            //    , txtDetail_Newoverfactor_Percent
            //    , txtDetail_Newjobfactor_Percent
            //    );

            //
            FormGlobals.TextBox_SetHandle(DataInputType.DateData, txtDetail_Fromdate, txtDetail_Todate);
            FormGlobals.TextBox_SetHandle(txtDocument_Month, DataInputType.IntegerData, 1, 12);

            FormGlobals.TextBox_SetHandle(DataInputType.NumberData,
                txtDocument_Social, txtDocument_Medical, txtDocument_Unemployed, txtDocument_Basicsalary,
                txtDetail_Socialrate, txtDetail_Medicalrate, txtDetail_Unemployedrate
                //Mức cũ, mức mới
                , txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor, txtDetail_Oldjobfactor_Percent, txtDetail_Oldareafactor,
                txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor_Percent, txtDetail_Newoverfactor, txtDetail_Newjobfactor, txtDetail_Newjobfactor_Percent, txtDetail_Newareafactor
                );

            FormGlobals.TextBox_SetFormat(Globals.CS_DISPLAY_RATE_FORMAT,
                txtDocument_Social, txtDocument_Medical, txtDocument_Unemployed,
                txtDetail_Socialrate, txtDetail_Medicalrate, txtDetail_Unemployedrate
                //Mức cũ, mức mới
                , txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor, txtDetail_Oldjobfactor_Percent, txtDetail_Oldareafactor,
                txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor_Percent, txtDetail_Newoverfactor, txtDetail_Newjobfactor, txtDetail_Newjobfactor_Percent, txtDetail_Newareafactor
                );

            FormGlobals.TextBox_SetFormat(Globals.CS_DISPLAY_MONTHYEAR_FORMAT, txtDetail_Fromdate, txtDetail_Todate);
            FormGlobals.TextBox_GetHandle(txtDetail_Fromdate).DateTime_SetVisibleIcon(false);
            FormGlobals.TextBox_GetHandle(txtDetail_Todate).DateTime_SetVisibleIcon(false);

            FormGlobals.TextBox_SetHandle(DataInputType.IntegerData, txtDocument_Month, txtDocument_Year, txtDetail_Newoverfactor_Percent, txtDetail_Newjobfactor_Percent, txtDetail_Oldoverfactor_Percent, txtDetail_Oldjobfactor_Percent);
            FormGlobals.TextBox_SetFormat(Globals.CS_DISPLAY_NUMBER_WITHOUT_FORMAT, txtDocument_Year);
            FormGlobals.TextBox_SetCase(CharacterCasing.Upper, txtDocument_Branchcode, txtDetail_Instypecode);
            
            //Do column vẫn khác tên cột
            //FormGlobals.Panel_SetFormField(grbPhatSinh, "HRM_BHDetail");

            //InstallTabIndex();
            //this.Textbox_SetKeyNextPreGroup(grbPhatSinh);
            
            //FormGlobals.Control_SetStyle(Color.White, txtDocumentDate, txtPeriod, txtMonth, txtYear, txtDocument_Social, txtDocument_Medical, txtDocument_Unemployed, txtBasicSalary);
            //
            FormGlobals.Control_SetVisible(false, lstEmployee);
            FormGlobals.Control_SetViewOnly(txtDetail_Totalmonth, txtDocument_Date);
            FormGlobals.Control_SetVisible(_Type == InsuranceType.HS, grbMucCu, grbMucMoi);
            FormGlobals.Control_SetVisible(_Type != InsuranceType.HS, grbMucMoiTien, grbMucCuTien);
            //Set quyền thao tác trên các nút
            FormGlobals.ToolStrip_SetViewOnly(!_listRole._create, btnNew, btnNewDocument, (ToolStripItem)btnGetData, (ToolStripItem)btnTNN, (ToolStripItem)btnTNKVK);
            FormGlobals.ToolStrip_SetViewOnly(!_listRole.Update, btnSave);
            FormGlobals.ToolStrip_SetViewOnly(!_listRole._delete, btnDelete);
            //
            FormGlobals.ToolStrip_SetViewOnly(_Approved != 1, btnNewDocument, btnSave, btnNew, btnDelete, btnGetData, btnDelAll, btnImportExcel, btnLayDuLieu);
            FormGlobals.ToolStrip_SetViewOnly(_Type == InsuranceType.ML, btnTNKVK, btnTNN);
            FormGlobals.ToolStrip_SetVisible(Program.strUserName.ToLower() == "vvtuy", btnDelAll); //Tạm thời chỉ để user vvtuy được quyền xóa cả document_id
            //
            //hiepdh: 19_02 sửa để chỉ vvtuy hoặc admin có quyền tạo chứng từ tạm khóa ko cho đơn vị dùng
            //Sau này mở chỉ cần bỏ dòng này
            //if (!_listRole._create || Program.strUserName.ToLower() != "vvtuy" || !Program.isAdmin)
            //    btnNewDocument.Enabled = false;

            //Set Required các ô nhập
            FormGlobals.Control_SetRequired(true, false, txtDetail_Insbookno, txtDetail_Fromdate, txtDetail_Todate, txtDetail_Instypecode, txtDetail_Socialrate, txtDetail_Medicalrate, txtDetail_Unemployedrate,
                txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor, txtDetail_Oldjobfactor_Percent, txtDetail_Oldareafactor,
                txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor_Percent, txtDetail_Newoverfactor, txtDetail_Newjobfactor, txtDetail_Newjobfactor_Percent, txtDetail_Newareafactor
                , txtDetail_PositionName
                );

            Init_Grid();
            //
            txtDocument_Branchcode.Text = Program.strBranchCode;
            txtDetail_Fromdate.Text = txtDetail_Todate.Text = _ViewDate.ToString("MM/yyyy");

            //FormGlobals.Control_SetDefault(txtKeyWord, btnFilter_Click);

            //Autocomplete danh sách chức danh
            int counter = 0;
            DataTable dtGrade = Position_Controller.Instance().Position_GetList(out counter, Program.strBranchCode, 0, 9999).Tables[0];
            new AutoCompleteTextBox_Handle(txtDetail_PositionName, dtGrade, "Position_Name");
            //
            Bind_Data();
            //

            //Nếu có danh sách thai sản đến hạn cần ON thì hiển thị
            //Da chot ky thi ko hien danh sach canh bao thai san nua
            if (_Approved == 1)
            {
                bool hasTS = false;
                FormGlobals.App_ProgressShow(delegate()
                {
                    hasTS = Detail_Controller.Instance().HasWarningTS(Program.intBranchID);
                }, "Kiểm tra danh sách nghỉ thai sản hết hạn, cần ON");
                //
                if (hasTS)
                {
                    SaveHeader();
                    //
                    frmGetNewDataList_TS f = new frmGetNewDataList_TS(_HeaderInfo
                , Convert.ToDecimal(txtDocument_Medical.Text)
                , Convert.ToDecimal(txtDocument_Unemployed.Text)
                , Convert.ToDecimal(txtDocument_Social.Text)
                , _ViewDate
                );

                    if (f.Show_Form(this) == DialogResult.OK)
                    {
                        LoadList();
                        //
                        MessageBox.Show("Đã hoàn thành lấy dữ liệu, kiểm tra kỳ đầu tiên");
                    }
                }
            }
        }

        //Bind dữ liệu
        private void Bind_Data()
        {
            if (_DocumentID > 0)
            {
                arg_HeaderID = Header_GetList();
                _HeaderInfo = BhHeader_Controller.Instance().Header_GetInfo(_DocumentID);
                HeaderInfo2Form();
                LoadRate(); //lấy tỷ lệ thu và mức lương tối thiểu theo đúng
                LoadSalary();
                //
                LoadList();
            }
            else
            {
                _RateInfo = new RateInfo();
                _RateInfo = Rate_Controller.Instance().Rate_GetMax();
                //
                txtDocument_Branchcode.Text = Program.strBranchBHXH;
                txtDocument_Date.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
                txtDocument_Month.Text = _ViewDate.Month.ToString();
                txtDocument_Year.Text = _ViewDate.Year.ToString().Replace(",", "").Replace(".", "");
                //FormGlobals.Panel_FillData(grbChung,
                FormGlobals.Control_SetValue(txtDocument_Social, _RateInfo.Rate_Social);
                FormGlobals.Control_SetValue(txtDocument_Medical, _RateInfo.Rate_Medical);
                FormGlobals.Control_SetValue(txtDocument_Unemployed, _RateInfo.Rate_Unemployed);

                //-Lấy mức lương tối thiểu theo đúng thời điểm tương ứng với danh mục lương tối thiểu
                txtDocument_Basicsalary.Text = _wcfSalary.BasicSalary_GetInfoByDate(_ViewDate).Amount.ToString(UIParamater.Phay2So);
            }
            //
            txtDetail_Insbookno.Focus();
        }


        //Lấy Document Id, để chuyển kỳ phát sinh
        DataTable dtHeader = new DataTable();
        int _index = 0;

        //Lấy danh sách các kỳ phát sinh, header đã đạo ra
        private int[] Header_GetList()
        {
            if (_DocumentID > 0)
            {
                int itemCount = 0;
                dtHeader = BhHeader_Controller.Instance().Header_GetList(out itemCount, Pager.PageIndex, UIParamater.PAGE_SIZE_MAX, Program.strBranchBHXH, _ViewDate.Month, _ViewDate.Year, _Type).Tables[0];
                //
                int[] tracks = new int[dtHeader.Rows.Count];
                for (int i = 0; i < dtHeader.Rows.Count; i++)
                {
                    tracks[i] = Convert.ToInt32(dtHeader.Rows[i]["Document_ID"]);
                    if (_DocumentID == tracks[i])
                        _index = i;
                }
                //
                //Pager.PageIndex = 0;
                Pager.PageSize = 1;
                Pager.TotalRow = dtHeader.Rows.Count;

                //
                return tracks;
            }
            else
            {
                return null;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //Lấy dữ liệu từ object nên form
        void HeaderInfo2Form()
        {
            FormGlobals.Panel_FillData(grbChung, _HeaderInfo);
            txtDocument_Date.Text = _HeaderInfo.Document_Date.ToString(Globals.CS_DISPLAY_DATE_FORMAT);
            if (_HeaderInfo.Document_Period <= 0)
                _HeaderInfo.Document_Period = 1;
            txtDocument_Period.SetText(_HeaderInfo.Document_Period, "");
            isChange = false;
        }

        protected override void Control_Validated(object sender, EventArgs e)
        {
            //
            switch ((sender as Control).Name.ToUpper())
            {
                case "TXTDETAIL_DESCRIPTION":
                    btnSave.Select(); //focus tới nút lưu
                    break;
            }
            // base.Control_Validated(sender, e);
        }

        //Lấy dữ liệu từ object Header fill lên form
        void HeaderForm2Info()
        {
            _HeaderInfo = new HeaderInfo();
            FormGlobals.Panel_GetData(grbChung, _HeaderInfo);
            _HeaderInfo.Document_Date = UISetting.GetDate(txtDocument_Date.Text);
            _HeaderInfo.Document_Id = _DocumentID;
            _HeaderInfo.Document_Type = _Type;
            _HeaderInfo.Document_Isinitial = false;
        }

        //Lấy dữ liệu nhập chi tiết Detail gán vào object
        void DetailForm2Info()
        {
            _DetailInfo = new DetailInfo();
            FormGlobals.Panel_GetData(grbPhatSinh, _DetailInfo);
            _DetailInfo.Detail_Id = _DetailID;
            _DetailInfo.Detail_Documentid = _DocumentID;
            _DetailInfo.Detail_Type = _Type;
            _DetailInfo.Detail_Status = (int)DetailStatus.Save;
            //
            _DetailInfo.Detail_Insbookno = txtDetail_Insbookno.Text.Trim();
            EmployeeInfo employeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(_DetailInfo.Detail_Insbookno);
            _DetailInfo.Detail_Employeecode = employeeInfo.Code;
            _DetailInfo.Detail_Regioncode = !String.IsNullOrEmpty(employeeInfo.MedicalRegionCode) ? employeeInfo.MedicalRegionCode : Program.strRegionCode;
            _DetailInfo.Detail_Hospitalcode = _MedicalPlace;
            //Chi đóng tiền thì mới có
            _DetailInfo.Detail_Newamount = _Type == InsuranceType.ML ? txtNewAmount.GetValue<decimal>() : 0;
            _DetailInfo.Detail_Oldamount = _Type == InsuranceType.ML ? txtOldAmount.GetValue<decimal>() : 0;
            
            //Lấy lương cơ bản
            _DetailInfo.Detail_Basicsalary = BasicSalary(_DetailInfo.Detail_Fromdate);
        }

        void DetailInfo()
        {
            _DetailInfoNew = new DetailInfo();
            _DetailInfoNew.Detail_Id = _DetailID;
            _DetailInfoNew.Detail_Documentid = _DocumentID;
            _DetailInfoNew.Detail_Insbookno = txtDetail_Insbookno.Text.Trim();
            _DetailInfoNew.Detail_Employeecode = _wcfEmployee.Employee_GetInfoBySIBookNo(_DetailInfo.Detail_Insbookno).Code;
            _DetailInfoNew.Detail_Fromdate = UISetting.GetDate(txtDetail_Todate.Text);
            _DetailInfoNew.Detail_Totalmonth = Convert.ToInt32(txtCountMonth.Text);
            if (_DetailInfoNew.Detail_Totalmonth > 0)
                _DetailInfoNew.Detail_Todate = _DetailInfoNew.Detail_Fromdate.AddMonths(_DetailInfoNew.Detail_Totalmonth - 1);
            else
                _DetailInfoNew.Detail_Todate = _DetailInfoNew.Detail_Fromdate;
            _DetailInfoNew.Detail_Instypecode = DetailInstypecode.TT;
            _DetailInfoNew.Detail_Socialrate = 0;
            _DetailInfoNew.Detail_Medicalrate = UISetting.GetDecimalNo(_RateInfo.Rate_Medical.ToString()); //UISetting.GetDecimalNo(txtEmployee_Medical.Text);
            _DetailInfoNew.Detail_Unemployedrate = 0;

            _DetailInfoNew.Detail_Oldbasicfactor = 0;
            _DetailInfoNew.Detail_Oldpositionfactor = 0;
            _DetailInfoNew.Detail_Oldoverfactor = 0;
            _DetailInfoNew.Detail_Oldjobfactor = 0;
            _DetailInfoNew.Detail_Oldareafactor = 0;

            _DetailInfoNew.Detail_Newbasicfactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
            _DetailInfoNew.Detail_Newpositionfactor = UISetting.GetDecimalNo(txtDetail_Oldpositionfactor.Text);
            _DetailInfoNew.Detail_Newoverfactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor.Text);
            _DetailInfoNew.Detail_Newjobfactor = UISetting.GetDecimalNo(txtDetail_Oldjobfactor.Text);
            _DetailInfoNew.Detail_Newareafactor = UISetting.GetDecimalNo(txtDetail_Oldareafactor.Text);

            _DetailInfoNew.Detail_Regioncode = "";
            _DetailInfoNew.Detail_Hospitalcode = "";
            _DetailInfoNew.Detail_Newamount = UISetting.GetDecimalNo(txtOldAmount.Text);
            _DetailInfoNew.Detail_Oldamount = 0;
            _DetailInfoNew.Detail_Type = _Type;
            _DetailInfoNew.Detail_Takecard = cbxDetail_Takecard.Checked;
            _DetailInfoNew.Detail_Status = (int)DetailStatus.Save;
            _DetailInfoNew.Detail_PositionName = txtDetail_PositionName.Text.Trim();
            _DetailInfoNew.Detail_Description = txtDetail_Description.Text.Trim();
        }

        //Khởi tạo danh sách cho grid
        DataGridHandle m_GridHandle;
        protected void Init_Grid()
        {
            List<DataGridViewColumn> arrColumn = new List<DataGridViewColumn>();
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BH", "Detail_InsBookNo", 80));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên", "Employee_FullName", 120));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Từ tháng", "Detail_FromDate", 70, Globals.CS_DISPLAY_MONTHYEAR_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Đến tháng", "Detail_ToDate", 70, Globals.CS_DISPLAY_MONTHYEAR_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số tháng", "Detail_TotalMonth", 60));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("PA", "Detail_InsTypeCode", 40));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ghi chú", "Detail_Description", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Chức vụ", "Detail_PositionName", 0));
            if (_Type == InsuranceType.ML)
            {
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ML mới", "Detail_NewAmount", 70, Globals.CS_DISPLAY_NUMBER_FORMAT));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ML cũ", "Detail_OldAmount", 70, Globals.CS_DISPLAY_NUMBER_FORMAT));
            }
            else if (_Type == InsuranceType.HS)
            {
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("HSL mới", "Detail_NewBasicFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Cvụ mới", "Detail_NewPositionFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("TNVK mới", "Detail_NewOverFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("TNN mới", "Detail_NewJobFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("KV mới", "Detail_NewAreaFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("HSL cũ", "Detail_OldBasicFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Cvụ cũ", "Detail_OldPositionFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("TNVK cũ", "Detail_OldOverFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("TNN cũ", "Detail_OldJobFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("KV cũ", "Detail_OldAreaFactor", 0, Globals.CS_DISPLAY_NUMBER_FORMAT, false));
                //Lương
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mức mới", "Detail_NewTotal", 70, Globals.CS_DISPLAY_RATE_FORMAT));
                arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mức cũ", "Detail_OldTotal", 70, Globals.CS_DISPLAY_RATE_FORMAT));
            }
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Tăng", "BSTang_BHXH", 80, Globals.CS_DISPLAY_NUMBER_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Giảm", "BSGiam_BHXH", 80, Globals.CS_DISPLAY_NUMBER_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Tăng", "BSTang_BHYT", 80, Globals.CS_DISPLAY_NUMBER_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Giảm", "BSGiam_BHYT", 80, Globals.CS_DISPLAY_NUMBER_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Tăng", "BSTang_BHTN", 80, Globals.CS_DISPLAY_NUMBER_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Giảm", "BSGiam_BHTN", 80, Globals.CS_DISPLAY_NUMBER_FORMAT));
            //
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("BHXH", "Detail_SocialRate", 50, Globals.CS_DISPLAY_RATE_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("BHYT", "Detail_MedicalRate", 50, Globals.CS_DISPLAY_RATE_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("BHTN", "Detail_UnemployedRate", 50, Globals.CS_DISPLAY_RATE_FORMAT));
            //
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("MLTT", "Document_BasicSalary", 70, Globals.CS_DISPLAY_NUMBER_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("HS/ML", "Detail_Type", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Thu thẻ", "Detail_TakeCard", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Detail_ID", "Detail_ID", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ID Ctừ", "Detail_DocumentID", 0));
            //
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("HS/ML", "Detail_Oldoverfactor_Percent", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Thu thẻ", "Detail_Oldjobfactor_Percent", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Detail_ID", "Detail_Newoverfactor_Percent", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ID Ctừ", "Detail_Newjobfactor_Percent", 0));
            //
            m_GridHandle = FormGlobals.Grid_Init(dgvList, arrColumn, "", 1);
            m_GridHandle.KeepMergeHeader = true;

            //m_GridHandle.Column_MergeHeader("Bổ sung", "BSTang_BHXH", 6);
            m_GridHandle.Column_MergeHeader("BHXH", "BSTang_BHXH", 2);
            m_GridHandle.Column_MergeHeader("BHYT", "BSTang_BHYT", 2);
            m_GridHandle.Column_MergeHeader("BHTN", "BSTang_BHTN", 2);

            m_GridHandle.Column_MergeHeader("Tỷ lệ thu", "Detail_SocialRate", 3);
            m_GridHandle.AllowFilter = true;
            m_GridHandle.Column_Sort += new DataGridHandle.Column_SortEventHandler(m_GridHandle_Column_Sort);
            //
        }

        void m_GridHandle_Column_Sort(string columnName, SortOrder e)
        {
            string s = columnName;
        }

        //Hiển thị danh sách phát sinh lên grid
        void LoadList()
        {
            int rowCount = 0;
            //
            if (_DocumentID > 0)
            {
                int itemCount = 0;
                DataSet _ds = Detail_Controller.Instance().Detail_GetList(out itemCount, Pager.PageIndex, UIParamater.PAGE_SIZE_MAX, _DocumentID);
                //
                rowCount = _ds.Tables[0].Rows.Count;
                dtQTBHTrongKy = _ds.Tables[0];
                //
                if (!dtQTBHTrongKy.Columns.Contains("Detail_NewTotal"))
                {
                    dtQTBHTrongKy.Columns.Add("Detail_NewTotal", typeof(decimal));
                    dtQTBHTrongKy.Columns.Add("Detail_OldTotal", typeof(decimal));
                }
                //Đặt cột để tự động tính theo công thức số tổng
                dtQTBHTrongKy.Columns["Detail_NewTotal"].Expression = "Detail_NewBasicFactor + Detail_NewPositionFactor + Detail_NewOverFactor+ Detail_NewJobFactor + Detail_NewAreaFactor";
                dtQTBHTrongKy.Columns["Detail_OldTotal"].Expression = "Detail_OldBasicFactor + Detail_OldPositionFactor + Detail_OldOverFactor+ Detail_OldJobFactor + Detail_OldAreaFactor";
                //
                dgvList.DataSource = dtQTBHTrongKy;
            }
            else
            {
                if (dtQTBHTrongKy != null)
                    dtQTBHTrongKy.Clear();
                if (dgvList.Rows.Count > 0)
                    dgvList.Rows.Clear();
            }
            //
            grbDSPhatSinh.Text = String.Format(lblDsPhatSinh, rowCount);
        }

        //kiểm tra dữ liệu nhập
        bool CheckValid()
        {
            //Check phương án DC
            if (_Type == InsuranceType.HS && txtDetail_Instypecode.Text.Trim().ToUpper() == "DC")
            {
                if (Convert.ToDecimal(txtDetail_Oldbasicfactor.Text) == 0 || Convert.ToDecimal(txtDetail_Newbasicfactor.Text) == 0)
                {
                    MessageBox.Show("Mức lương phải lớn hơn 0", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            //
            if (_Type == InsuranceType.HS && ("GD, GH, GC, GN, OF, TS").IndexOf(txtDetail_Instypecode.Text) >= 0 && Convert.ToDecimal(txtDetail_Newbasicfactor.Text) > 0)
            {
                txtDetail_Newbasicfactor.Focus();
                MessageBox.Show("Mức lương mới phải bằng 0", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            if (txtDetail_Insbookno.Text.ToString().Length != 10)
            {
                txtDetail_Insbookno.Focus();
                MessageBox.Show("Số sổ bảo hiểm phải đủ 10 ký tự", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            //
            if (txtDetail_Instypecode.Text.Trim().ToUpper() != "CD")
            {
                if (("TT,TU").IndexOf(txtDetail_Instypecode.Text) >= 0 && Convert.ToDecimal(txtDetail_Medicalrate.Text) <= 0)
                {
                    txtDetail_Medicalrate.Focus();
                    MessageBox.Show("Tỷ lệ BHYT không hợp lệ", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                if (("TN,GN,DN,TT,TU").IndexOf(txtDetail_Instypecode.Text) < 0 && Convert.ToDecimal(txtDetail_Socialrate.Text) <= 0)
                {
                    txtDetail_Socialrate.Focus();
                    MessageBox.Show("Tỷ lệ BHXH không hợp lệ", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            //Kiểm tra khoảng thời gian phát sinh đã tồn tại
            //Không thể điều chỉnh nhiều lần trong 1 lần quyết toán
            DateTime fromDate = UISetting.GetDate(txtDetail_Fromdate.Text);
            DateTime toDate = UISetting.GetDate(txtDetail_Todate.Text);
            DateTime currDate = UISetting.GetDate((txtDocument_Month.Text.Length == 1 ? "0" + txtDocument_Month.Text : txtDocument_Month.Text) + "/" + txtDocument_Year.Text.Replace(",", "").Replace(".", ""));

            if (fromDate < new DateTime(2009, 01, 01) && Convert.ToDecimal(txtDetail_Unemployedrate.Text) > 0)
            {
                MessageBox.Show("Trước tháng 01/2009 không được tham gia BHTN");
                return false;
            }
            decimal sumofhsml = 0;
            if (dtQTBHXH.Rows.Count > 0)
                sumofhsml = (decimal)dtQTBHXH.Rows[0]["Premium_Salary"] + (decimal)dtQTBHXH.Rows[0]["Premium_BasicFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_PositionFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_SeniorityFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_OverSeniorityFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_AreaFactor"];
            if (dtQTBHTN.Rows.Count == 0 && (dtQTBHXH.Rows.Count > 0 && sumofhsml > 0) && Convert.ToDecimal(txtDetail_Unemployedrate.Text) > 0 && ("TN,GN,DN").IndexOf(txtDetail_Instypecode.Text) < 0)
            {
                MessageBox.Show("Mức lương tham gia BHTN không hợp lệ");
                return false;
            }

            if (Convert.ToDecimal(txtDetail_Oldbasicfactor.Text) == Convert.ToDecimal(txtDetail_Newbasicfactor.Text) &&
                Convert.ToDecimal(txtDetail_Oldpositionfactor.Text) == Convert.ToDecimal(txtDetail_Newpositionfactor.Text) &&
                Convert.ToDecimal(txtDetail_Oldoverfactor.Text) == Convert.ToDecimal(txtDetail_Newoverfactor.Text) &&
                Convert.ToDecimal(txtDetail_Oldjobfactor.Text) == Convert.ToDecimal(txtDetail_Newjobfactor.Text)
                && Convert.ToDecimal(txtDetail_Oldbasicfactor.Text) != 0 && Convert.ToDecimal(txtDetail_Newbasicfactor.Text) != 0
                && _Type == "HS")
            {
                MessageBox.Show("Mức lương không hợp lệ");
                return false;
            }

            //Truong hop ML
            if (Convert.ToDecimal(txtOldAmount.Text) == Convert.ToDecimal(txtNewAmount.Text) && Convert.ToDecimal(txtOldAmount.Text) != 0 && _Type == "ML")
            {
                MessageBox.Show("Mức lương không hợp lệ");
                return false;
            }
            if (_Type == "ML")
            {
                if (Convert.ToDecimal(txtDetail_Oldbasicfactor.Text) > 23000000 || Convert.ToDecimal(txtDetail_Newbasicfactor.Text) > 23000000)
                {
                    MessageBox.Show("Mức lương không được phép vượt quá 23.000.000");
                    return false;
                }
            }
            //Truong hop HS
            if (_Type == "HS")
            {
                if (Convert.ToDecimal(txtDetail_Oldbasicfactor.Text) + Convert.ToDecimal(txtDetail_Oldpositionfactor.Text) + Convert.ToDecimal(txtDetail_Oldoverfactor.Text) + Convert.ToDecimal(txtDetail_Oldjobfactor.Text) + Convert.ToDecimal(txtDetail_Oldareafactor.Text) > 20)
                {
                    MessageBox.Show("Hệ số lương không được phép vượt quá 20,00");
                    return false;
                }
                if (Convert.ToDecimal(txtDetail_Newbasicfactor.Text) + Convert.ToDecimal(txtDetail_Newpositionfactor.Text) + Convert.ToDecimal(txtDetail_Newoverfactor.Text) + Convert.ToDecimal(txtDetail_Newjobfactor.Text) + Convert.ToDecimal(txtDetail_Newareafactor.Text) > 20)
                {
                    MessageBox.Show("Hệ số không được phép vượt quá 20,00");
                    return false;
                }
            }
            //
            DateTime periodDate = UISetting.GetDate("01/" + Convert.ToInt32(txtDocument_Month.Text).ToString("00") + "/" + txtDocument_Year.Text.Replace(",", "").Replace(".", ""));
            string PA = txtDetail_Instypecode.Text;
            if (dtQTBHTrongKy != null)
            {
                foreach (DataRow dr in dtQTBHTrongKy.Rows)
                {
                    string Detail_insBookNo = Convert.ToString(dr["Detail_InsBookNo"]);
                    string Detail_ID = Convert.ToString(dr["Detail_ID"]);

                    DateTime Detail_FromDate = Convert.ToDateTime(dr["Detail_FromDate"]);
                    DateTime Detail_ToDate = Convert.ToDateTime(dr["Detail_ToDate"]);

                    if (Detail_insBookNo.Equals(txtDetail_Insbookno.Text) &&
                            (
                                //07/05/2015 nếu truy thu nhiều phát sinh trong cùng 1 kỳ thì được
                                (fromDate >= periodDate) &&
                                (
                                (fromDate >= Detail_FromDate && fromDate <= Detail_ToDate) ||
                                (toDate >= Detail_FromDate && toDate <= Detail_ToDate)
                                )
                            )
                            && (_DetailID.ToString() != Detail_ID)
                            && !(PA == "TT" || PA == "TU")

                        )
                    {
                        MessageBox.Show("Không thể điều chỉnh nhiều lần trong một lần quyết toán");
                        txtDetail_Insbookno.Focus();
                        txtDetail_Insbookno.SelectAll();
                        return false;
                    }
                    else if (!(PA == "TT" || PA == "TU") && (toDate > periodDate))
                    {
                        MessageBox.Show("Mức lương điều chỉnh không hợp lệ");
                        return false;
                    }
                }
            }

            //19.09.14: băt buộc nhập chức danh
            //if (txtChucDanh.Text.Trim() == "" || txtChucDanh.Text.Trim().ToLower() == "không xác định")
            //{
            //    MessageBox.Show("Chưa nhập chức danh");
            //    return false;
            //}

            //kiểm tra truy thu quá 3 tháng thì cảnh báo
            //8/6/2013 hiepdh
            if (Globals.DateTime_MonthDiff(fromDate, currDate) >= 3 && PA != "CD")
            {
                MessageBox.Show("Truy thu quá 3 tháng đề nghị đơn vị làm công văn gửi cơ quan BHXH");
                //return false;
            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            dlgResult = DialogResult.Cancel;
            this.Close();
        }

        //Lưu dữ liệu Header
        bool SaveHeader()
        {
            if (_DocumentID > 0)//update
            {
                HeaderForm2Info();
                if (!BhHeader_Controller.Instance().Header_Update(_HeaderInfo))
                    return false;
            }
            else //Insert
            {
                HeaderForm2Info();
                _DocumentID = BhHeader_Controller.Instance().Header_Insert(_HeaderInfo);
                _HeaderInfo.Document_Id = _DocumentID;
                if (_DocumentID <= 0)
                    return false;
            }
            return true;
        }

        //Lưu dữ liệu chi tiết phát sinh
        bool SaveDetail()
        {
            DetailForm2Info();
            //if (CheckRateSalary(_DetailInfo.FromDate, _DetailInfo.ToDate))
            //    return false;
            TinhPhanTram();


            if (_DetailID > 0)//update
            {
                if (!Detail_Controller.Instance().Detail_Update(_DetailInfo))
                    return false;
            }
            else //Insert
            {
                if (txtDetail_Insbookno.Text.Length != 0)
                {
                    _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                    //else
                    //{
                    //    _DetailID = 0;
                    //    MessageBox.Show("Số sổ bảo hiểm này đã nhập khoảng thời gian đóng theo phương án này rồi!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //    return false;
                    //}
                    string _InsType = "";
                    _InsType = _DetailInfo.Detail_Instypecode;
                    switch (_InsType)
                    {
                        case "GC":
                        case "GD":
                        case "GH":
                        case "OF":
                        case "KL":
                            if (!_TakeCard)
                            {
                                _DetailID = 0;
                                DetailInfo();
                                _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfoNew);
                            }
                            break;
                    }
                }
                else
                {
                    _DetailID = 0;
                }
            }
            if (_DetailID <= 0)
                return false;
            return true;
        }

        private void TinhPhanTram()
        {
            decimal OldBasicFactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
            decimal OldPosionFactor = UISetting.GetDecimalNo(txtDetail_Oldpositionfactor.Text);
            decimal OldOverFactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor.Text);
            decimal OldJobFactor = UISetting.GetDecimalNo(txtDetail_Oldjobfactor.Text);
            //
            if (OldOverFactor != 0)
            {
                decimal OldOverFactor_Percent = (OldOverFactor * 100 / OldBasicFactor);
                _DetailInfo.Detail_Oldoverfactor_Percent = Globals.Object_GetValue<Int32>(Math.Round(OldOverFactor_Percent));
            }
            if (OldJobFactor != 0)
            {
                decimal OldJobFactor_Percnet = (OldJobFactor * 100 / (OldBasicFactor + OldPosionFactor + OldOverFactor));
                _DetailInfo.Detail_Oldjobfactor_Percent = Globals.Object_GetValue<Int32>(Math.Round(OldJobFactor_Percnet));
            }

            decimal NewBasicFactor = UISetting.GetDecimalNo(txtDetail_Newbasicfactor.Text);
            decimal NewPosionFactor = UISetting.GetDecimalNo(txtDetail_Newpositionfactor.Text);
            decimal NewOverFactor = UISetting.GetDecimalNo(txtDetail_Newoverfactor.Text);
            decimal NewJobFactor = UISetting.GetDecimalNo(txtDetail_Newjobfactor.Text);

            if (NewOverFactor != 0)
            {
                decimal NewOverFactor_Percent = (NewOverFactor * 100 / NewBasicFactor);
                _DetailInfo.Detail_Newoverfactor_Percent = Globals.Object_GetValue<Int32>(Math.Round(NewOverFactor_Percent));
            }
            if (NewJobFactor != 0)
            {
                decimal NewJobFactor_Percnet = (NewJobFactor * 100 / (NewBasicFactor + NewPosionFactor + NewOverFactor));
                _DetailInfo.Detail_Newjobfactor_Percent = Globals.Object_GetValue<Int32>(Math.Round(NewJobFactor_Percnet));
            }
        }


        //Lưu dữ liệu
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Panel_CheckError(grbPhatSinh))
                return;

            if (!CheckValid())
            {
                isChange = true;
                return;
            }

            if (!SaveHeader())
            {
                UISetting.MesNotUpdate();
                return;
            }
            if (!SaveDetail())
            {
                UISetting.MesNotUpdate();
                return;
            }


            //Kiểm tra nhân viên thôi việc, ON trở lại
            bool IsQuited = false;
            DataTable dtTmp = LocalDB.Employee_GetListByParameter(txtDetail_Insbookno.Text);
            if (dtTmp.Rows.Count == 1)
                IsQuited = Convert.ToBoolean(dtTmp.Rows[0]["Employee_IsQuited"]);

            if (IsQuited && txtDetail_Instypecode.Text == "ON")
            {
                LocalDB.dtTableEmployee.Select("Employee_SIBookNo='" + txtDetail_Insbookno.Text + "'")[0]["Employee_IsQuited"] = false;
                LocalDB.dtTableEmployee.AcceptChanges();

                //Hủy tick đã thôi việc, đánh dấu ON trở lại
                Employee_Controller.Instance().Employee_On(txtDetail_Insbookno.Text, Program.intBranchID);
            }

            //
            Program.taskbarNotifier.Show(UIParamater.TitleProject, "Cập nhật thành công!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
            dlgResult = DialogResult.OK;
            LoadList();
            _DetailID = 0;
            txtDetail_Fromdate.Text = txtDetail_Todate.Text = _ViewDate.ToString("MM/yyyy");
            txtDetail_Insbookno.Focus();

            FormGlobals.TextBox_SetValue(0, txtDetail_Oldbasicfactor, txtDetail_Newbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Newpositionfactor, txtDetail_Oldoverfactor, txtDetail_Newoverfactor, txtDetail_Oldjobfactor, txtDetail_Newjobfactor, txtDetail_Oldareafactor, txtDetail_Newareafactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldjobfactor_Percent, txtDetail_Newoverfactor_Percent, txtDetail_Newjobfactor_Percent);
            FormGlobals.TextBox_SetValue("", txtDetail_Insbookno, txtEmployee_FullName, txtDetail_PositionName, txtDetail_Description);
            FormGlobals.TextBox_SetValue(0, txtNewAmount, txtOldAmount);
            disable_readonly();
        }

        //Tạo kỳ phát sinh mới
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!_listRole.Create)
            {
                UISetting.MesNotRightNew();
                return;
            }
            _DetailID = 0;
            disable_readonly();
            NewText();
        }

        void NewText()
        {
            _RateInfo = Rate_Controller.Instance().Rate_GetMax();
            //
            txtDocument_Social.Text = txtDetail_Socialrate.Text = _RateInfo.Rate_Social.ToString("#0.0#");
            txtDocument_Medical.Text = txtDetail_Medicalrate.Text = _RateInfo.Rate_Medical.ToString("#0.0#");
            txtDocument_Unemployed.Text = txtDetail_Unemployedrate.Text = _RateInfo.Rate_Unemployed.ToString("#0.0#");
            txtDetail_Fromdate.Text = txtDetail_Todate.Text = _ViewDate.ToString("MM/yyyy");
            FormGlobals.TextBox_SetValue("", txtDetail_Insbookno, txtEmployee_FullName, txtDetail_Fromdate, txtDetail_PositionName);
            FormGlobals.TextBox_SetValue(0, txtOldAmount, txtNewAmount, txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor, txtDetail_Oldareafactor, txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor, txtDetail_Newjobfactor, txtDetail_Newareafactor, txtCountMonth);
            //
            txtDetail_Insbookno.Focus();
        }
        private void frmInsurance_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isChange)
            {
                if (MessageBox.Show(UpdateUI.GetString("bandathaydoidulieu") + "\n" + UpdateUI.GetString("coluutruockhithoatkhong"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                    if (isChange)
                        e.Cancel = true;
                    else
                        e.Cancel = false;
                }
            }
            this.DialogResult = dlgResult;
        }

        private void frmInsurance_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.N:
                    if (e.Control)
                        if (btnNew.Enabled)
                            btnNew_Click(null, null);
                    break;
                case Keys.F2:
                    if (btnNewDocument.Enabled)
                        btnNewDocument_Click(null, null);
                    break;
                case Keys.F3:
                    if (btnSave.Enabled)
                        btnSave_Click(null, null);
                    break;
                case Keys.Delete:
                    if (e.Control)
                        if (btnDelete.Enabled)
                            btnDelete_Click(null, null);
                    break;
                case Keys.Escape:
                    this.Close();
                    break;
                case Keys.Enter:
                    break;
            }
        }

        private void DataChange(object sender, EventArgs e)
        {
            isChange = true;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (UIParamater.Quyen_BaoCaoBHXH.View || UIParamater.Quyen_BaoCaoBHXH.Print)
            {
                frmInsuranceReport f = new frmInsuranceReport();
                if (f.ShowDialog() == DialogResult.OK)
                {
                    frmPreviewReport fReport = new frmPreviewReport(f.ReportType, new string[] { f.ReportText, f.Month, f.Year });
                    fReport.ShowDialog(this);
                }
            }
            else
                MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void txtMonth_Leave(object sender, EventArgs e)
        {
            LoadRate();
            LoadSalary();
        }

        void LoadRate()
        {
            DateTime _date = DateTime.MinValue;
            _date = UISetting.GetDate("01/" + Convert.ToInt32(txtDocument_Month.Text).ToString("00") + "/" + txtDocument_Year.Text.Replace(",", "").Replace(".", ""));
            _RateInfo = Rate_Controller.Instance().Rate_GetInfoByDate(_date);
            //
            txtDocument_Medical.Text = txtDetail_Medicalrate.Text = _RateInfo.Rate_Medical.ToString("#0.0#");
            txtDocument_Unemployed.Text = txtDetail_Unemployedrate.Text = _RateInfo.Rate_Unemployed.ToString("#0.0#");
            Current_UnemployedRate = _RateInfo.Rate_Unemployed;
            txtDocument_Social.Text = txtDetail_Socialrate.Text = _RateInfo.Rate_Social.ToString("#0.0#");
        }

        void LoadSalary()
        {
            DateTime _date = DateTime.MinValue;
            _date = UISetting.GetDate("01/" + Convert.ToInt32(txtDocument_Month.Text).ToString("00") + "/" + txtDocument_Year.Text.Replace(",", "").Replace(".", ""));
            _BasicSalaryInfo = _wcfSalary.BasicSalary_GetInfoByDate(_date);
            txtDocument_Basicsalary.Text = _BasicSalaryInfo.Amount.ToString("#,##0");
        }

        decimal BasicSalary(DateTime _Val)
        {
            decimal _Salary = 0;
            _BasicSalaryInfo = _wcfSalary.BasicSalary_GetInfoByDate(_Val);
            _Salary = _BasicSalaryInfo.Amount;
            return _Salary;
        }

        //Xóa 1 phát sinh
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                _DetailID = Convert.ToInt32(dgvList.SelectedRows[0].Cells["Detail_ID"].Value);

                if (!_listRole.Delete)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (Detail_Controller.Instance().Detail_Delete(_DetailID, 0))
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        _DetailID = 0;
                        txtDetail_Fromdate.Text = txtDetail_Todate.Text = _ViewDate.ToString("MM/yyyy");
                        txtDetail_Insbookno.Focus();
                        FormGlobals.TextBox_SetValue("", txtDetail_Insbookno, txtEmployee_FullName);
                        FormGlobals.TextBox_SetValue_AllChild(0, grbMucCu, grbMucMoi);
                        //
                        disable_readonly();
                        LoadList();
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }


        void Control_FillData_Format(string colName, ref object obj)
        {
            obj = obj;
        }

        //Chọn 1 row từ grid, hiển thị lại thông tin
        private void dgvList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            FormGlobals.App_ProgressShow(delegate()
            {
                disable_readonly();

                if (dgvList.SelectedRows.Count > 0)
                {
                    DataGridViewRow CurRow = dgvList.SelectedRows[0];
                    string PA = CurRow.GetValue<string>("Detail_InsTypeCode");
                    //
                    DataRowEx drEx = new DataRowEx((CurRow.DataBoundItem as DataRowView).Row);

                    ////Fill dữ liệu từ gridviewrow lên panel
                    FormGlobals.Control_FillData(grbPhatSinh.Controls, drEx, new FormatInvoker(Control_FillData_Format));

                    _DetailID = CurRow.GetValue<Int32>("Detail_ID");
                    ////-Fill các giá trị liên quan tỷ lệ thu và nhân viên
                    //txtDetail_Insbookno.Text = CurRow.Cells["Detail_InsBookNo"].Value.ToString();
                    //txtFullName.Text = CurRow.Cells["Employee_FullName"].Value.ToString();
                    //txtDetail_Instypecode.Text = CurRow.Cells["Detail_InsTypeCode"].Value.ToString();
                    ////-- 
                    //txtDetail_Socialrate.Text = Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_SocialRate"].Value).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                    //txtDetail_Medicalrate.Text = Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_MedicalRate"].Value).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                    //txtDetail_Unemployedrate.Text = Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_UnemployedRate"].Value).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                    //FormGlobals.Control_SetValue(txtDetail_Fromdate, CurRow.Cells["Detail_FromDate"].Value);
                    //FormGlobals.Control_SetValue(txtDetail_Todate, CurRow.Cells["Detail_ToDate"].Value);
                    //txtDetail_PositionName.Text = Convert.ToString(CurRow.Cells["Detail_PositionName"].Value);
                    //txtDetail_Description.Text = Convert.ToString(CurRow.Cells["Detail_Description"].Value);
                    //
                    dtQTBHXH = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text, 0,
                        Globals.DB_GetValue<DateTime>(CurRow.Cells["Detail_FromDate"].Value),
                        Globals.DB_GetValue<DateTime>(CurRow.Cells["Detail_ToDate"].Value),
                        _DocumentID).Tables[0];
                    //
                    dtQTBHTN = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text, 1,
                        Globals.DB_GetValue<DateTime>(CurRow.Cells["Detail_FromDate"].Value),
                        Globals.DB_GetValue<DateTime>(CurRow.Cells["Detail_ToDate"].Value),
                        _DocumentID).Tables[0];

                    //Lấy nơi khám chữa bệnh
                    DataTable dtMedicalPlace = Employee_GetOne(txtDetail_Insbookno.Text, txtEmployee_FullName.Text);
                    if (dtMedicalPlace.Rows.Count > 0)
                        _MedicalPlace = Employee_GetOne(txtDetail_Insbookno.Text, txtEmployee_FullName.Text).Rows[0][0].ToString();
                    //txtRegionCode.Text = SelectedRow.Cells["Detail_RegionCode"].Value.ToString();
                    //txtHospitalCode.Text = SelectedRow.Cells["Detail_HospitalCode"].Value.ToString();

                    if (_Type == "ML")
                    {
                        if (Convert.ToDecimal(CurRow.Cells["Detail_OldAmount"].Value) != 0 || CurRow.Cells["Detail_InsTypeCode"].Value.ToString() == "TM" || CurRow.Cells["Detail_InsTypeCode"].Value.ToString() == "ON")
                        {
                            txtOldAmount.ReadOnly = true;
                            txtOldAmount.BackColor = Color.White;
                        }
                        else
                        {
                            txtOldAmount.ReadOnly = false;
                        }
                        txtOldAmount.Text = Convert.ToDecimal(CurRow.Cells["Detail_OldAmount"].Value).ToString("#,##0");
                        txtNewAmount.Text = Convert.ToDecimal(CurRow.Cells["Detail_NewAmount"].Value).ToString("#,##0");
                    }
                    else if (_Type == "HS")
                    {
                        if (Convert.ToDecimal(CurRow.Cells["Detail_OldBasicFactor"].Value) != 0 || ("TM,ON,TT,TN").IndexOf(CurRow.Cells["Detail_InsTypeCode"].Value.ToString()) >= 0)
                        {
                            FormGlobals.Control_SetViewOnly(true, grbMucCu);
                        }
                        else
                        {
                            FormGlobals.Control_SetViewOnly(false, grbMucCu);
                        }

                        ////Fill mức cũ, mức mới
                        //txtDetail_Oldbasicfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_OldBasicFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Oldpositionfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_OldPositionFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Oldoverfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_OldOverFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Oldjobfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_OldJobFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Oldareafactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_OldAreaFactor"].Value).ToString(UIParamater.Cham3So);

                        //txtDetail_Newbasicfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_NewBasicFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Newpositionfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_NewPositionFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Newoverfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_NewOverFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Newjobfactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_NewJobFactor"].Value).ToString(UIParamater.Cham3So);
                        //txtDetail_Newareafactor.Text = Convert.ToDecimal(CurRow.Cells["Detail_NewAreaFactor"].Value).ToString(UIParamater.Cham3So);


                        //Tính % của mức cũ khi lấy thông tin từ info=> form
                        txtDetail_Oldoverfactor_Percent.Text = "0";
                        txtDetail_Oldjobfactor_Percent.Text = "0";
                        decimal OldBasicFactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
                        decimal OldPosionFactor = UISetting.GetDecimalNo(txtDetail_Oldpositionfactor.Text);
                        decimal OldOverFactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor.Text);
                        decimal OldJobFactor = UISetting.GetDecimalNo(txtDetail_Oldjobfactor.Text);
                        //
                        FormGlobals.Control_SetValue(txtDetail_Oldoverfactor_Percent, Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_Oldoverfactor_Percent"].Value));
                        FormGlobals.Control_SetValue(txtDetail_Oldjobfactor_Percent, Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_Oldjobfactor_Percent"].Value));
                        //Tính % của mức mới khi lấy thông tin từ info=> form
                        FormGlobals.Control_SetValue(txtDetail_Newoverfactor_Percent, Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_Newoverfactor_Percent"].Value));
                        FormGlobals.Control_SetValue(txtDetail_Newjobfactor_Percent, Globals.Object_GetValue<Decimal>(CurRow.Cells["Detail_Newjobfactor_Percent"].Value));
                    }

                    txtDetail_Totalmonth.Text = CurRow.GetValue<String>("Detail_TotalMonth");
                    cbxDetail_Takecard.Checked = CurRow.GetValue<Boolean>("Detail_TakeCard");
                    //
                    _fromDate = txtDetail_Fromdate.GetValue_Form<DateTime>();
                    _toDate = txtDetail_Todate.GetValue_Form<DateTime>();


                    //Khóa các tỷ lệ thu BHXH,BHYT,BHTN dựa trên Phương ÁN, không cho phép sửa
                    switch (PA)
                    {
                        case "TT":
                        case "TU":
                            //Khóa tỷ lệ thu BHXH, TN
                            FormGlobals.Control_SetViewOnly(true,
                                txtDetail_Socialrate,
                                txtDetail_Unemployedrate);
                            break;
                        case "GC":
                        case "GD":
                        case "GH":
                        case "OF":
                        case "KL":
                            //Khóa tỷ lệ thu BHYT
                            FormGlobals.Control_SetViewOnly(true, txtDetail_Medicalrate);
                            break;
                        case "TN":
                        case "GN":
                            //Khóa tỷ lệ thủ BHXH, BHYT
                            FormGlobals.Control_SetViewOnly(true,
                                txtDetail_Socialrate,
                                txtDetail_Medicalrate);
                            break;
                    }

                    //Khóa mức mới dựa trên phương án
                    if (("TN,DN,TT,TU,GH,GC,GD,OF,TS,KL").Contains(PA))
                    {
                        FormGlobals.Control_SetViewOnly(true, grbMucMoi);
                    }

                    //hiepdh: KHóa ô nhập % TNN và TNVK trong trường hợp nhân sự này đc tick ko tính TNN và TNVK bên nhân sự
                    KhongTinhTNNvsTNVK(txtDetail_Insbookno.Text);
                }
            }, "Loading...");
        }

        private void txtYear_Leave(object sender, EventArgs e)
        {
            LoadRate();
            LoadSalary();
        }

        //Tự động hiển thị danh sách nhân sự theo số sổ nhập
        void AutoCompleteEmployee(string Parameter)
        {
            try
            {
                lstEmployee.Items.Clear();
                DataTable dtGL = LocalDB.Employee_GetListByParameter(Parameter.ToLower());
                ListViewItem item;
                if (dtGL != null)
                    for (int i = 0; i < dtGL.Rows.Count; i++)
                    {
                        item  = new ListViewItem(dtGL.Rows[i]["Employee_SIBookNo"].ToString());
                        
                        item.SubItems.Add(dtGL.Rows[i]["FullName"].ToString());
                        //item.Name = dtGL.Rows[i]["FullName"].ToString();
                        item.Name = dtGL.Rows[i]["Employee_SIBookNo"].ToString();
                        item.SubItems.Add(Convert.ToDateTime(dtGL.Rows[i]["Employee_DateOfBirth"]).ToString("dd/MM/yyyy"));
                        item.SubItems.Add(dtGL.Rows[i]["Employee_ID"].ToString());
                        //Chỉ hiển thị danh sách nhân sự thuộc branch hiện tại
                        if (Convert.ToInt32(dtGL.Rows[i]["Employee_BranchID"]) == Program.intBranchID
                            //&& !Convert.ToBoolean(dtGL.Rows[i]["Employee_IsQuited"])
                            )
                        {
                            if(Convert.ToBoolean(dtGL.Rows[i]["Employee_IsQuited"]))
                                item.ForeColor = Color.Red;
                            lstEmployee.Items.Add(item);
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Autocomplete: " + ex.ToString());
            }
        }

        private void txtSIBookNo_TextChanged(object sender, EventArgs e)
        {
            if (txtDetail_Insbookno.Focused)
            {
                if (txtDetail_Insbookno.Text.Length > 0)
                {
                    AutoCompleteEmployee(txtDetail_Insbookno.Text);
                    if (lstEmployee.Items.Count > 0)
                    {
                        lstEmployee.Visible = true;
                        lstEmployee.HeaderStyle = ColumnHeaderStyle.None;
                        lstEmployee.BringToFront();
                        lstEmployee.Items[0].Selected = true;
                    }
                    else
                        lstEmployee.Visible = false;
                }
                else
                    lstEmployee.Visible = false;


            }
        }

        private void txtSIBookNo_Enter(object sender, EventArgs e)
        {
            txtDetail_Insbookno.SelectAll();
        }
        string _MedicalPlace = "";

        private void txtSIBookNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (lstEmployee.Items.Count > 0 && lstEmployee.Visible)
                {
                    lstEmployee.Focus();
                    for (int i = 0; i < lstEmployee.Items.Count; i++)
                    {
                        if (lstEmployee.Items[i].Selected)
                        {
                            txtDetail_Insbookno.Text = lstEmployee.Items[i].SubItems[0].Text;
                            txtEmployee_FullName.Text = lstEmployee.Items[i].SubItems[1].Text;
                            _EmployeeID = Convert.ToInt32(lstEmployee.Items[i].SubItems[3].Text);
                            _MedicalPlace = "";
                            DataTable dt = Employee_GetOne(txtDetail_Insbookno.Text, txtEmployee_FullName.Text);
                            if(dt.Rows.Count > 0)
                                _MedicalPlace = dt.Rows[0][0].ToString();
                        }
                    }

                }
            }
            //else if (e.KeyCode == Keys.Right && (txtDetail_Insbookno.SelectionLength == txtDetail_Insbookno.Text.Length || txtDetail_Insbookno.SelectionStart == txtDetail_Insbookno.Text.Length))
            //{
            //    if (sender is TextBox)
            //    {
            //        this.ProcessTabKey(true);
            //        ((TextBox)sender).SelectAll();
            //        e.Handled = true;
            //    }
            //}
            //else if (e.KeyCode == Keys.Left && (txtDetail_Insbookno.SelectionLength == txtDetail_Insbookno.Text.Length || txtDetail_Insbookno.SelectionStart == 0))
            //{
            //    if (sender is TextBox)
            //    {
            //        this.ProcessTabKey(false);
            //        ((TextBox)sender).SelectAll();
            //        e.Handled = true;
            //    }
            //}
            else if (e.KeyCode == Keys.Enter)
            {
                if (lstEmployee.Items.Count == 1 && lstEmployee.Visible)
                {
                    txtDetail_Insbookno.Text = lstEmployee.Items[0].SubItems[0].Text;
                    txtEmployee_FullName.Text = lstEmployee.Items[0].SubItems[1].Text;
                    _EmployeeID = Convert.ToInt32(lstEmployee.Items[0].SubItems[2].Text);
                    txtDetail_Insbookno.SelectAll();
                    lstEmployee.Visible = false;
                }
                else
                    lstEmployee.Visible = false;
            }
        }

        private DataTable Employee_GetOne(string sibookno, string fullname)
        {
            DataTable dt = new DataTable();
            DataColumn dcol = null;
            dcol = new DataColumn("Employee_MedicalPlace", typeof(string));
            dt.Columns.Add(dcol);

            if (LocalDB.dtTableEmployee != null && LocalDB.dtTableEmployee.Rows.Count > 0)
            {
                //Trích xuất dữ liệu từ dtRoot 
                DataRow[] dr1 = LocalDB.dtTableEmployee.Select("Employee_SIBookNo='" + sibookno + "' and FULLNAME = '" + fullname + "'", "");

                //Gán các dòng dữ liệu trích ra được vào bảng mới tạo
                for (int i = 0; i < dr1.Length; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["Employee_MedicalPlace"] = Globals.DB_GetValue<string>(dr1[i]["Employee_MedicalPlace"]);
                    dt.Rows.InsertAt(dr, i);
                }
            }
            return dt;
        }
        private void lstEmployee_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (lstEmployee.Items.Count > 0)
                {
                    for (int i = 0; i < lstEmployee.Items.Count; i++)
                    {
                        if (lstEmployee.Items[i].Selected)
                        {
                            lstEmployee.Items[i].BackColor = Color.Yellow;
                            txtDetail_Insbookno.Text = lstEmployee.Items[i].SubItems[0].Text;
                            txtEmployee_FullName.Text = lstEmployee.Items[i].SubItems[1].Text;
                            _EmployeeID = Convert.ToInt32(lstEmployee.Items[i].SubItems[3].Text);
                        }
                    }
                }
                lstEmployee.SendToBack();
                txtDetail_Insbookno.Focus();
                lstEmployee.Visible = false;
            }
        }

        private void lstEmployee_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            for (int i = 0; i < lstEmployee.Items.Count; i++)
            {
                if (lstEmployee.Items[i].Selected)
                {
                    txtDetail_Insbookno.Text = lstEmployee.Items[i].SubItems[0].Text;
                    txtEmployee_FullName.Text = lstEmployee.Items[i].SubItems[1].Text;
                }
            }
            lstEmployee.SendToBack();
            txtDetail_Insbookno.Focus();
            lstEmployee.Visible = false;
        }

        //Tạo kỳ mới
        private void btnNewDocument_Click(object sender, EventArgs e)
        {
            _DocumentID = 0;
            disable_readonly();
            LoadList();
            txtDocument_Date.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
            txtDocument_Period.Text = (Convert.ToInt32(txtDocument_Period.Text) + 1).ToString();
            NewText();
            LoadSalary();
        }

        private void txtSIBookNo_Leave(object sender, EventArgs e)
        {
            if (txtDetail_Insbookno.Text.Length > 0)
            {
                //Kiểm tra HS ML
                DateTime ToDateTmp = DateTime.MinValue;
                string LastestHSML = Detail_Controller.Instance().GetLastestHSML(txtDetail_Insbookno.Text, out ToDateTmp);
                if (_Type != LastestHSML && LastestHSML != "")
                {
                    if (MessageBox.Show("Thông tin lương không hợp lệ (" + Program.strBranchBHXH + " - " + LastestHSML + " - " + " đến tháng : " + ToDateTmp.ToString("MM/yyyy") + " ). Có tiếp tục không?", "Thông tin lương không hợp lệ", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    {
                        txtEmployee_FullName.Text = "";
                        txtDetail_Insbookno.Text = "";
                        txtDetail_Insbookno.Focus();
                    }
                }

            }
        }
        void LoadOldSalary()
        {
            DateTime _DateFrom = DateTime.MinValue;
            DateTime docDate = DateTime.MinValue;
            DateTime _dateMax = DateTime.MinValue;
            if (DateTextBox.Date_TryParseEx(txtDetail_Fromdate.Text, ref docDate))
                _DateFrom = docDate;
            _EmployeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(txtDetail_Insbookno.Text.Trim());
            if (_EmployeeInfo != null)
            {
                DataTable dtPD = new DataTable();
                DataTable dtN = new DataTable();
                int n = 0;
                dtN = _wcfPremium.Premium_GetBySIBookNo(txtDetail_Insbookno.Text.Trim(), true).Tables[0];
                if (dtN.Rows.Count > 0)
                    _dateMax = Convert.ToDateTime(dtN.Rows[0]["Premium_FromDate"]);
                dtPD = _wcfPremium.Premium_GetAmount(_DateFrom, txtDetail_Insbookno.Text.Trim()).Tables[0];
                n = dtPD.Rows.Count;
                if (n > 0)
                {
                    if (_DetailID == 0)//Neu tao moi thi lay muc luong cu da co:
                    {
                        txtOldAmount.Text = Convert.ToDecimal(dtPD.Rows[0]["Amount"]).ToString("#,##0");
                        txtDetail_Oldbasicfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["BasicFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldpositionfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["PositionFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldoverfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["OverFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldjobfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["JobFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldareafactor.Text = Convert.ToDecimal(dtPD.Rows[0]["AreaFactor"]).ToString(UIParamater.Cham3So);

                        txtNewAmount.Text = "0";
                        txtDetail_Newbasicfactor.Text = "0";
                        txtDetail_Newpositionfactor.Text = "0";
                        txtDetail_Newoverfactor.Text = "0";
                        txtDetail_Newjobfactor.Text = "0";
                        txtDetail_Newareafactor.Text = "0";
                    }
                }
                else if (_DateFrom >= _dateMax)
                {
                    if (dtN.Rows.Count > 0)
                    {
                        txtOldAmount.Text = Convert.ToDecimal(dtN.Rows[0]["Premium_Salary"]).ToString("#,##0");
                        txtDetail_Oldbasicfactor.Text = Convert.ToDecimal(dtN.Rows[0]["Premium_BasicFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldpositionfactor.Text = Convert.ToDecimal(dtN.Rows[0]["Premium_PositionFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldoverfactor.Text = Convert.ToDecimal(dtN.Rows[0]["Premium_OverSeniorityFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldjobfactor.Text = Convert.ToDecimal(dtN.Rows[0]["Premium_SeniorityFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Oldareafactor.Text = Convert.ToDecimal(dtN.Rows[0]["Premium_AreaFactor"]).ToString(UIParamater.Cham3So);
                    }
                    else
                    {
                        txtOldAmount.Text = "0";
                        txtDetail_Oldbasicfactor.Text = "0";
                        txtDetail_Oldpositionfactor.Text = "0";
                        txtDetail_Oldoverfactor.Text = "0";
                        txtDetail_Oldjobfactor.Text = "0";
                        txtDetail_Oldareafactor.Text = "0";
                    }
                    txtNewAmount.Text = "0";
                    txtDetail_Newbasicfactor.Text = "0";
                    txtDetail_Newpositionfactor.Text = "0";
                    txtDetail_Newoverfactor.Text = "0";
                    txtDetail_Newjobfactor.Text = "0";
                    txtDetail_Newareafactor.Text = "0";
                }
                else
                {
                    txtOldAmount.Text = "0";
                    txtDetail_Oldbasicfactor.Text = "0";
                    txtDetail_Oldpositionfactor.Text = "0";
                    txtDetail_Oldoverfactor.Text = "0";
                    txtDetail_Oldjobfactor.Text = "0";
                    txtDetail_Oldareafactor.Text = "0";

                    txtNewAmount.Text = "0";
                    txtDetail_Newbasicfactor.Text = "0";
                    txtDetail_Newpositionfactor.Text = "0";
                    txtDetail_Newoverfactor.Text = "0";
                    txtDetail_Newjobfactor.Text = "0";
                    txtDetail_Newareafactor.Text = "0";
                }
            }
            //
            //
            //Tính % của mức cũ khi lấy thông tin từ info=> form
            decimal OldBasicFactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
            decimal OldPosionFactor = UISetting.GetDecimalNo(txtDetail_Oldpositionfactor.Text);
            decimal OldOverFactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor.Text);
            decimal OldJobFactor = UISetting.GetDecimalNo(txtDetail_Oldjobfactor.Text);

            //
            if (OldOverFactor != 0)
            {
                decimal OldOverFactor_Percent = (OldOverFactor * 100 / OldBasicFactor);
                txtDetail_Oldoverfactor_Percent.Text = Math.Round(OldOverFactor_Percent).ToString();
            }
            if (OldJobFactor != 0)
            {
                decimal OldJobFactor_Percnet = (OldJobFactor * 100 / (OldBasicFactor + OldPosionFactor + OldOverFactor));
                txtDetail_Oldjobfactor_Percent.Text = Math.Round(OldJobFactor_Percnet).ToString();
            }
        }

        //Kiểm tra giá trị khi nhập vào ô từ tháng
        //Lấy các tỷ lệ thu tương ứng
        private void txtFromDate_Validated(object sender, EventArgs e)
        {
            if (txtDetail_Insbookno.IsNotEmpty())
            {
                FormGlobals.App_ProgressShow(delegate()
                {
                    _fromDate = txtDetail_Fromdate.GetValue<DateTime>();

                    if (_fromDate != DateTime.MinValue)
                    {
                        _RateInfo = Rate_Controller.Instance().Rate_GetInfoByDate(_fromDate);
                        //
                        txtDetail_Medicalrate.SetText(_RateInfo.Rate_Medical, Globals.CS_DISPLAY_RATE_FORMAT);
                        txtDetail_Unemployedrate.SetText(_RateInfo.Rate_Unemployed, Globals.CS_DISPLAY_RATE_FORMAT);
                        txtDetail_Socialrate.SetText(_RateInfo.Rate_Social, Globals.CS_DISPLAY_RATE_FORMAT);
                    }
                }, "kiểm tra từ tháng...");
            }
        }

        //Kiểm tra giá trị nhập vào ô đến tháng
        //
        private void txtToDate_Validated(object sender, EventArgs e)
        {
            if (txtDetail_Insbookno.IsEmpty())
                return;
            //
            FormGlobals.App_ProgressShow(delegate()
            {
                if (txtDetail_Fromdate.IsNotEmpty() && txtDetail_Todate.IsNotEmpty())
                {
                    _fromDate = txtDetail_Fromdate.GetValue<DateTime>();
                    _toDate = txtDetail_Todate.GetValue<DateTime>();
                    //
                    if (_fromDate > _toDate)
                    {
                        MessageBox.Show("Tháng bắt đầu không được lớn hơn tháng kết thúc!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        //
                        txtDetail_Fromdate.Focus();
                        return;
                    }

                    //Trường hợp nhập mới, lấy tổng số tháng và chức danh gần nhất theo phát sinh
                    if (_DetailID == 0)
                    {
                        txtDetail_Totalmonth.SetText(CountMonth(_fromDate, _toDate, _ViewDate, ""), "");
                        string PositionName = Detail_Controller.Instance().GetPositionName(_fromDate, _toDate, txtDetail_Insbookno.Text.Trim(), txtDocument_Branchcode.Text.Trim(),0);
                        _PDInfo = _wcfPositionDetal.PositionDetail_GetInfo(_EmployeeID);
                        if (_PDInfo != null)
                        {
                            if (_PDInfo.PositionID != 0)
                            {
                                _PositionInfo = _wcfPosition.Position_GetInfo(_PDInfo.PositionID);
                            }
                        }
                        txtDetail_PositionName.Text = !String.IsNullOrEmpty(PositionName) ? PositionName.Trim() : _PositionInfo.Name;
                    }

                    //GetQuaTrinhBHXH(_fromDate,_toDate);
                    //Nếu có 2 bản ghi quá trình BHXH hoặc BHYT thì cảnh báo
                    dtQTBHXH = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text.Trim(), 0, _fromDate, _toDate, _DocumentID).Tables[0];
                    dtQTBHTN = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text.Trim(), 1, _fromDate, _toDate, _DocumentID).Tables[0];
                    //
                    if (txtDetail_Instypecode.IsNotEmpty())
                    {
                        if (!CheckQTBHTmp(dtQTBHXH, "XH"))
                        {
                            txtDetail_Todate.SetFocus_SelectAll();
                            return;
                        }
                    }
                }
            }, "kiểm tra đến tháng...");
        }


        //Đếm số tháng theo từ ngày đến ngày
        public int CountMonth(DateTime fromDate, DateTime toDate, DateTime viewDate, string PA)
        {
            int retVal = 0;
            if (fromDate == toDate && toDate < viewDate)
                retVal = 1;
            else if (_fromDate == _toDate && _toDate == _ViewDate)
                retVal = 0;
            else if ((_fromDate == _ViewDate || _toDate == _ViewDate) && _fromDate < _toDate)
                retVal = UISetting.GetMonth(_fromDate, _toDate);
            else
                retVal = UISetting.GetMonth(_fromDate, _toDate) + 1;

            //Xét th TT hoặc TU
            if ((PA == "TT" || PA == "TU") && (toDate >= viewDate))
                retVal += 1;

            return retVal;
        }

        //Hàm tạm, xem thêm
        public void PopupQTBHXH_TN(DataTable dtQTBH)
        {
            //Thông báo fải nhập thành nhiều giai đoạn
            frmInsuranceInfo frm = new frmInsuranceInfo(dtQTBH,
                txtDetail_Insbookno.Text,
                txtEmployee_FullName.Text,
                "",
                txtDetail_Newbasicfactor.Text,
                txtDetail_Newpositionfactor.Text,
                txtDetail_Newoverfactor.Text,
                txtDetail_Newjobfactor.Text,
                txtDetail_Newareafactor.Text,
                txtNewAmount.Text
                );
            frm.FormClosed += new FormClosedEventHandler(frm_FormInsuaranceInfoClosed);
            frm.afterEnterOnDatagridRow += new frmInsuranceInfo.AfterEnterOnDatagridRow(frm_afterEnterOnDatagridRow);
            frm.ShowDialog();
        }

        public bool CheckQTBHTmp(DataTable dtQTBH, string Type)
        {
            if (dtQTBH == null)
                return true;

            //11/1/2014: bỏ qua đóng trùng thời điểm ở các đơn vị khác nhau

            if (dtQTBH.Rows.Count > 1)
            {
                dtQTBH = dtQTBH.Select("Premium_Workunit='" + Program.strBranchCode + "'").CopyToDataTable();
            }


            if (dtQTBH.Rows.Count > 1 && txtDetail_Instypecode.Text.Trim().ToUpper() != "CD")
            {
                PopupQTBHXH_TN(dtQTBH);
                return false;
            }
            else if (dtQTBH.Rows.Count == 1)
            {

                //11/1/2014: Bỏ qua kiểm tra nhập trùng quá trình trong cùng thời điểm ở đơn vị khác nhau
                //vvtuy:bảo bỏ

                string Work_Unit = Convert.ToString(dtQTBH.Rows[0]["Premium_WorkUnit"]);
                if (Work_Unit.ToUpper() != Program.strBranchCode.ToUpper())
                {
                    if (MessageBox.Show("Giai đoạn này đã đóng bảo hiểm tại đơn vị (khác): " + Work_Unit + "\n" + "Bạn có tiếp tục không?", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        txtDetail_Todate.SetFocus_SelectAll();
                        return false;
                    }
                }
                else
                {
                    //chỉ kiểm tra với các PA khác CD
                    if (txtDetail_Instypecode.Text.Trim().ToUpper() != "CD")
                    {
                        //Tu thang va den thang cua ban ghi qua trinh fai = tu thang va den thang cua qua trinh nhap vao
                        //if ((_fromDate != Convert.ToDateTime(dtQTBH.Rows[0]["Premium_FromDate"]) || _toDate != Convert.ToDateTime(dtQTBH.Rows[0]["Premium_ToDate"])))
                        if (_fromDate != Convert.ToDateTime(dtQTBH.Rows[0]["Premium_FromDate"]) && _toDate != _ViewDate)
                        {
                            if (MessageBox.Show("Thời gian điều chỉnh quá trình BHXH không cùng mức lương", "Thông báo", MessageBoxButtons.OK) == DialogResult.OK)
                            {
                                PopupQTBHXH_TN(dtQTBH);
                                return false;
                            }
                        }

                        //Kiểm tra giao nhau với quá trình đóng bảo hiểm thất nghiệp
                        //Từ tháng và đến tháng của TN fải nằm trong Từ THáng đến tháng của Xã Hội
                        if (Type == "XH" && dtQTBHTN.Rows.Count > 1)
                        {
                            PopupQTBHXH_TN(dtQTBHTN);
                            return false;
                        }
                        else if (Type == "XH" && dtQTBHTN.Rows.Count == 1)
                        {
                            DateTime _fromDateTN = Convert.ToDateTime(dtQTBHTN.Rows[0]["Premium_FromDate"]);
                            DateTime _toDateTN = Convert.ToDateTime(dtQTBHTN.Rows[0]["Premium_ToDate"]);

                            DateTime _fromDateInput = UISetting.GetDate(txtDetail_Fromdate.Text.Trim());
                            DateTime _toDateInput = UISetting.GetDate(txtDetail_Todate.Text.Trim());

                            if ((_fromDateTN != _fromDateInput || _toDateTN != _toDateInput) && dtQTBHTrongKy != null && ("TT,TU").IndexOf(txtDetail_Instypecode.Text) < 0)
                            {
                                if (MessageBox.Show("Thời gian này có giao thoa quá trình tham gia bảo hiểm thất nghiệp không cùng mức lương, bạn có muốn xem quá trình thất nghiệp không", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    PopupQTBHXH_TN(dtQTBHTN);
                                    //LockForm(txtToDate);
                                    return false;
                                }
                            }

                            //if(!(( _fromDateTN>= _fromDate && _fromDateTN <= _toDate)&&
                            //   ( _toDateTN>= _fromDate && _toDateTN <= _toDate)))
                            //{
                            //    MessageBox.Show("Thời gian đóng bảo hiểm thất nghiệp không cùng mức lương");
                            //    PopupQTBHXH_TN(dtQTBHTN);
                            //    return false;
                            //}
                        }
                    }


                    //Nếu qua hết các điều kiện, Fill dữ liệu theo hệ số
                    if (_Type == "HS")
                    {
                        txtDetail_Oldbasicfactor.Text = GetDecimalValueUtil(dtQTBH.Rows[0]["Premium_BasicFactor"], UIParamater.Cham3So);
                        txtDetail_Oldpositionfactor.Text = GetDecimalValueUtil(dtQTBH.Rows[0]["Premium_PositionFactor"], UIParamater.Cham3So);
                        txtDetail_Oldoverfactor.Text = GetDecimalValueUtil(dtQTBH.Rows[0]["Premium_OverSeniorityFactor"], UIParamater.Cham3So);
                        txtDetail_Oldjobfactor.Text = GetDecimalValueUtil(dtQTBH.Rows[0]["Premium_SeniorityFactor"], UIParamater.Cham3So);
                        txtDetail_Oldareafactor.Text = GetDecimalValueUtil(dtQTBH.Rows[0]["Premium_AreaFactor"], UIParamater.Cham3So);

                        //Tính % của mức cũ khi lấy thông tin từ info=> form
                        txtDetail_Oldoverfactor_Percent.Text = "0";
                        txtDetail_Oldjobfactor_Percent.Text = "0";
                        decimal OldBasicFactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
                        decimal OldPosionFactor = UISetting.GetDecimalNo(txtDetail_Oldpositionfactor.Text);
                        decimal OldOverFactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor.Text);
                        decimal OldJobFactor = UISetting.GetDecimalNo(txtDetail_Oldjobfactor.Text);
                        //
                        if (OldOverFactor != 0)
                        {
                            decimal OldOverFactor_Percent = (OldOverFactor * 100 / OldBasicFactor);
                            txtDetail_Oldoverfactor_Percent.Text = Math.Round(OldOverFactor_Percent).ToString();
                        }
                        if (OldJobFactor != 0)
                        {
                            decimal OldJobFactor_Percnet = (OldJobFactor * 100 / (OldBasicFactor + OldPosionFactor + OldOverFactor));
                            txtDetail_Oldjobfactor_Percent.Text = Math.Round(OldJobFactor_Percnet).ToString();
                        }
                    }
                    else if (_Type == "ML")
                    {
                        txtOldAmount.Text = GetDecimalValueUtil(dtQTBH.Rows[0]["Premium_Salary"], UIParamater.Phay2So);
                        txtNewAmount.Text = "0";
                    }
                }
            }
            return true;
        }

        void frm_afterEnterOnDatagridRow(DateTime fromDate, DateTime toDate)
        {
            txtDetail_Fromdate.Text = fromDate.ToString("MM/yyyy");
            txtDetail_Todate.Text = toDate.ToString("MM/yyyy");
            txtFromDate_Validated(null, null);
            //
            //txtDetail_Todate.SetFocus_SelectAll();
            txtToDate_Validated(null, null);
            //
            txtDetail_Instypecode.SetFocus_SelectAll();
        }

        public void frm_FormInsuaranceInfoClosed(object sender, EventArgs args)
        {
            ((frmInsuranceInfo)sender).Dispose();
        }

        //-------Xem thêm
        private void GetQuaTrinhBHXH(DateTime _fromDate, DateTime _toDate)
        {
            dtQTBHXH = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text.Trim(), 0, _fromDate, _toDate, 0).Tables[0];
            switch (dtQTBHXH.Rows.Count)
            {
                case 0:
                    //Clear mức cũ
                    FormGlobals.Panel_ClearData(grbMucCu);
                    break;
                case 1:
                    //Fill vào mức cũ
                    string Work_Unit = Convert.ToString(dtQTBHXH.Rows[0]["Premium_WorkUnit"]);
                    if (Work_Unit != Program.strBranchCode)
                    {
                        FormGlobals.Panel_ClearData(grbMucCu);
                    }
                    else
                    {
                        txtDetail_Oldbasicfactor.Text = GetDecimalValueUtil(dtQTBHXH.Rows[0]["Premium_BasicFactor"], UIParamater.Cham3So);
                        txtDetail_Oldpositionfactor.Text = GetDecimalValueUtil(dtQTBHXH.Rows[0]["Premium_PositionFactor"], UIParamater.Cham3So);
                        txtDetail_Oldoverfactor.Text = GetDecimalValueUtil(dtQTBHXH.Rows[0]["Premium_OverSeniorityFactor"], UIParamater.Cham3So);
                        txtDetail_Oldjobfactor.Text = GetDecimalValueUtil(dtQTBHXH.Rows[0]["Premium_SeniorityFactor"], UIParamater.Cham3So);
                        txtDetail_Oldareafactor.Text = GetDecimalValueUtil(dtQTBHXH.Rows[0]["Premium_AreaFactor"], UIParamater.Cham3So);
                    }
                    break;
                default:
                    //Clear mức cũ, đợi khi lưu sẽ hiện popup danh sách quá trình
                    FormGlobals.Panel_ClearData(grbMucCu);
                    //frmInsuranceInfo frm = new frmInsuranceInfo(dtQTBH, _Type);
                    //frm.ShowDialog();
                    break;
            }
        }

        //Nếu từ tháng -> đến tháng có thay đổi tỷ lệ thu thì phải tách giai đoạn nhập
        bool CheckRateSalary(DateTime _FVal, DateTime _TVal)
        {
            bool _Found = false;
            if (Rate_Controller.Instance().Rate_CheckDate(_FVal, _TVal))
            {
                MessageBox.Show("Từ tháng -> đến tháng có thay đổi tỷ lệ thu, cần nhập tách giai đoạn!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _Found = true;
                //
                txtDetail_Fromdate.SetFocus_SelectAll();
            }
            return _Found;
        }

        //Kiểm tra lương
        void CheckSalary()
        {
            FormGlobals.App_ProgressShow(delegate()
            {
                DataTable dtDate = _wcfPremium.Premium_GetBySIBookNo(txtDetail_Insbookno.Text.Trim(), true).Tables[0];
                DateTime _dateFrom = DateTime.MinValue;
                DateTime _dateCompare = DateTime.MinValue;
                DateTime docDate = DateTime.MinValue;
                //
                if (DateTextBox.Date_TryParseEx(txtDetail_Fromdate.Text, ref docDate))
                    _dateFrom = docDate;
                //
                if (dtDate.Rows.Count > 0)
                {
                    _dateCompare = Convert.ToDateTime(dtDate.Rows[dtDate.Rows.Count - 1]["Premium_FromDate"]);
                    if (_dateFrom < _dateCompare)
                    {
                        FormGlobals.Panel_ClearData(grbMucCu);
                    }
                }
                else
                {
                    FormGlobals.Panel_ClearData(grbMucCu);
                }
            }, "Kiểm tra mức lương");
        }

        #region cho phép import danh sách phát sinh
        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Excel file (*.xls)|*.xls";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                InputData(openFileDialog.FileName);
            }
        }
        private void InputData(string FileName)
        {
            int row = 0;
            string col = "";

            List<DetailInfo> lstInfo = new List<DetailInfo>();
            try
            {
                DataSet ds = ReadExcelFile.ReadExcelList(FileName);
                DataTable dt = ds.Tables[0];
                DataTable dt1;

                decimal decVal = 0;
                int intVal = 0;
                bool boolVal;

                foreach (DataRow dr in dt.Rows)
                {
                    row++;
                    _DetailInfo = new DetailInfo();
                    _DetailInfo.Detail_Id = 0;

                    col = "SOBHXH";
                    _DetailInfo.Detail_Insbookno = Convert.ToString(dr[col]).Trim();

                    col = "HOTEN";
                    _EmployeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(_DetailInfo.Detail_Insbookno);
                    if (_EmployeeInfo != null)
                        _DetailInfo.Detail_Employeecode = _EmployeeInfo.Code;
                    else
                        _DetailInfo.Detail_Employeecode = "";

                    //col = "MA_TINH";
                    //_DetailInfo.RegionCode = Convert.ToString(dr[col]).Trim();

                    //col = "MA_BV";
                    //_DetailInfo.HospitalCode = Convert.ToString(dr[col]).Trim();

                    _DetailInfo.Detail_Type = _Type;
                    col = "ML_DK";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        if (_Type == "ML")
                            _DetailInfo.Detail_Oldamount = decVal;
                        else
                            _DetailInfo.Detail_Oldbasicfactor = decVal;

                    col = "PC1_DK";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Oldpositionfactor = decVal;

                    col = "PC2_DK";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Oldoverfactor = decVal;

                    col = "PC3_DK";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Oldjobfactor = decVal;

                    col = "PC4_DK";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Oldareafactor = decVal;

                    col = "ML";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        if (_Type == "ML")
                            _DetailInfo.Detail_Newamount = decVal;
                        else
                            _DetailInfo.Detail_Newbasicfactor = decVal;

                    col = "PC1";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Newpositionfactor = decVal;

                    col = "PC2";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Newoverfactor = decVal;

                    col = "PC3";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Newjobfactor = decVal;

                    col = "PC4";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                        _DetailInfo.Detail_Newareafactor = decVal;

                    col = "TUTHANG";
                    if (dr[col].ToString().Trim().Length > 0)
                        _DetailInfo.Detail_Fromdate = DateTime.ParseExact(dr[col].ToString().Trim(), "MM/yyyy", null);
                    else
                        _DetailInfo.Detail_Fromdate = DateTime.MinValue;

                    col = "DENTHANG";
                    if (dr[col].ToString().Trim().Length > 0)
                        _DetailInfo.Detail_Todate = DateTime.ParseExact(dr[col].ToString().Trim(), "MM/yyyy", null);
                    else
                        _DetailInfo.Detail_Todate = DateTime.MinValue;

                    col = "TYLE";
                    if (Decimal.TryParse(dr[col].ToString().Trim(), out decVal))
                    {
                        if (decVal == Convert.ToDecimal("28.5"))
                        {
                            _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("4.5");
                            _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal("2");
                            _DetailInfo.Detail_Socialrate = Convert.ToDecimal("22");
                        }
                        else if (decVal == Convert.ToDecimal("26.5"))
                        {
                            _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("4.5");
                            _DetailInfo.Detail_Unemployedrate = 0;
                            _DetailInfo.Detail_Socialrate = Convert.ToDecimal("22");
                        }
                        else if (decVal == Convert.ToDecimal("25"))
                        {
                            _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("3");
                            _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal("2");
                            _DetailInfo.Detail_Socialrate = Convert.ToDecimal("20");
                        }
                        else if (decVal == Convert.ToDecimal("23"))
                        {
                            _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("3");
                            _DetailInfo.Detail_Unemployedrate = 0;
                            _DetailInfo.Detail_Socialrate = Convert.ToDecimal("20");
                        }
                        else if (decVal == Convert.ToDecimal("4.5"))
                        {
                            _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("4.5");
                            _DetailInfo.Detail_Unemployedrate = 0;
                            _DetailInfo.Detail_Socialrate = 0;
                        }
                        else if (decVal == Convert.ToDecimal("3"))
                        {
                            _DetailInfo.Detail_Medicalrate = Convert.ToDecimal("3");
                            _DetailInfo.Detail_Unemployedrate = 0;
                            _DetailInfo.Detail_Socialrate = 0;
                        }
                        else if (decVal == Convert.ToDecimal("2"))
                        {
                            _DetailInfo.Detail_Medicalrate = 0;
                            _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal("2");
                            _DetailInfo.Detail_Socialrate = 0;
                        }
                    }
                    else
                    {
                        _DetailInfo.Detail_Medicalrate = 0;
                        _DetailInfo.Detail_Unemployedrate = 0;
                        _DetailInfo.Detail_Socialrate = 0;
                    }

                    col = "TRATHE";
                    if (Convert.ToString(dr[col]).ToUpper().Trim() == "X")
                    {
                        _DetailInfo.Detail_Takecard = true;
                        _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;
                    }
                    else
                    {
                        _DetailInfo.Detail_Takecard = false;
                        _DetailInfo.Detail_Totalmonth = 0;
                    }

                    col = "GHICHU";
                    //_DetailInfo.de = Convert.ToString(dr[col]).Trim();

                    col = "PA";
                    _DetailInfo.Detail_Instypecode = Convert.ToString(dr[col]).ToUpper().Trim();
                    _DetailInfo.Detail_Regioncode = "";
                    _DetailInfo.Detail_Hospitalcode = "";

                    lstInfo.Add(_DetailInfo);
                }
                col = "";
                dgvList.Rows.Clear();
                for (int i = 0; i < lstInfo.Count; i++)
                {
                    dgvList.Rows.Insert(i, 1);
                    dgvList.Rows[i].Cells["Detail_ID"].Value = 0;
                    dgvList.Rows[i].Cells["Detail_DocumentID"].Value = _DocumentID;
                    dgvList.Rows[i].Cells["Detail_InsBookNo"].Value = lstInfo[i].Detail_Insbookno;
                    _EmployeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(lstInfo[i].Detail_Insbookno);
                    if (_EmployeeInfo != null)
                        dgvList.Rows[i].Cells["Employee_FullName"].Value = _EmployeeInfo.LastName + " " + _EmployeeInfo.FirstName;
                    else
                        dgvList.Rows[i].Cells["Employee_FullName"].Value = "";
                    dgvList.Rows[i].Cells["Detail_FromDate"].Value = lstInfo[i].Detail_Fromdate.ToString("MM/yyyy");
                    dgvList.Rows[i].Cells["Detail_ToDate"].Value = lstInfo[i].Detail_Todate.ToString("MM/yyyy");
                    dgvList.Rows[i].Cells["Detail_InsTypeCode"].Value = lstInfo[i].Detail_Instypecode;
                    dgvList.Rows[i].Cells["Detail_SocialRate"].Value = lstInfo[i].Detail_Socialrate.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_MedicalRate"].Value = lstInfo[i].Detail_Medicalrate.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_UnemployedRate"].Value = lstInfo[i].Detail_Unemployedrate.ToString(UIParamater.Cham3So);
                    //dgvList.Rows[i].Cells["Detail_RegionCode"].Value = _ds.Tables[0].Rows[i]["Detail_RegionCode"].ToString();
                    //dgvList.Rows[i].Cells["Detail_HospitalCode"].Value = _ds.Tables[0].Rows[i]["Detail_HospitalCode"].ToString();
                    //dgvList.Rows[i].Cells["Detail_Description"].Value =lstInfo[i].de .ToString();
                    dgvList.Rows[i].Cells["Detail_NewBasicFactor"].Value = lstInfo[i].Detail_Newbasicfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_NewPositionFactor"].Value = lstInfo[i].Detail_Newpositionfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_NewOverFactor"].Value = lstInfo[i].Detail_Newoverfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_NewJobFactor"].Value = lstInfo[i].Detail_Newjobfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_NewAreaFactor"].Value = lstInfo[i].Detail_Newareafactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_OldBasicFactor"].Value = lstInfo[i].Detail_Oldbasicfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_OldPositionFactor"].Value = lstInfo[i].Detail_Oldpositionfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_OldOverFactor"].Value = lstInfo[i].Detail_Oldoverfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_OldJobFactor"].Value = lstInfo[i].Detail_Oldjobfactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_OldAreaFactor"].Value = lstInfo[i].Detail_Oldareafactor.ToString(UIParamater.Cham3So);
                    dgvList.Rows[i].Cells["Detail_NewAmount"].Value = lstInfo[i].Detail_Newamount.ToString("#,##0");
                    dgvList.Rows[i].Cells["Detail_OldAmount"].Value = lstInfo[i].Detail_Oldamount.ToString("#,##0");
                    dgvList.Rows[i].Cells["Detail_Type"].Value = lstInfo[i].Detail_Type;
                    dgvList.Rows[i].Cells["Detail_TakeCard"].Value = lstInfo[i].Detail_Takecard.ToString();
                }
                //int i = 0;
                int j = 0;
                int k = 0;
                string duplicateInsNo = "";
                if (_DocumentID > 0)
                {
                    foreach (DetailInfo item in lstInfo)
                    {
                        item.Detail_Documentid = _DocumentID;
                        if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                        {
                            if (Detail_Controller.Instance().Detail_Insert(item) > 0)
                                j = j + 1;
                        }
                    }
                }
                else
                {
                    //lstVehicleInfo.AddRange(lstInfo);
                }
                string strMessage = "Cập nhật thành công " + j.ToString() + " dòng!";
                if (k > 0)
                    strMessage += "\nTrong đó có " + k.ToString() + " dòng trùng số liệu là: " + duplicateInsNo;

                strMessage += "\nKết quả có " + (j - k).ToString() + " số phát sinh được cập nhật thêm.";

                MessageBox.Show(strMessage, "Thông báo", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                //lstVehicleInfo.Clear();
                MessageBox.Show("Lỗi xảy ra: \nDòng: " + row.ToString() + "\nCột: " + col + "\n" + ex.Message, "Thông báo", MessageBoxButtons.OK);
            }

        }
        #endregion


        //Lấy dữ liệu bên nhân sự
        //Lấy dữ liệu những bản ghi bên nhân sự, tạo phát sinh tự động với phương án ON/TM
        //Lấy nhân sự => nhân sự đóng bảo hiểm
        private void btnGetData_Click(object sender, EventArgs e)
        {
            frmGetNewDataList f = new frmGetNewDataList(_listRole);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                string[] _ArrID = f.SelectedID.Split(',');


                for (int i = 0; i < _ArrID.Length; i++)
                {
                    if (_ArrID[i].Length > 0)
                    {
                        //Insert Header:
                        SaveHeader();

                        //Insert Detail:
                        _EmployeeID = Convert.ToInt32(_ArrID[i]);
                        
                        _EmployeeInfo = _wcfEmployee.Employee_GetInfo(_EmployeeID);
                        _PDInfo = _wcfPositionDetal.PositionDetail_GetInfo(_EmployeeID);
                        if (_PDInfo != null)
                        {
                            if (_PDInfo.PositionID != 0)
                            {
                                _PositionInfo = _wcfPosition.Position_GetInfo(_PDInfo.PositionID);
                            }
                        }
                        _DetailID = 0;
                        _DetailInfo = new DetailInfo();
                        _DetailInfo.Detail_Documentid = _DocumentID;
                        _DetailInfo.Detail_Insbookno = _EmployeeInfo.SIBookNo;
                        _DetailInfo.Detail_Employeecode = _EmployeeInfo.Code;
                        _DetailInfo.Detail_Fromdate = _PDInfo.BeginDate;
                        _DetailInfo.Detail_Todate = _ViewDate;
                        //_DetailInfo.ToDate = _PDInfo.BeginDate;
                        _DetailInfo.Detail_Instypecode = "TM";
                        _DetailInfo.Detail_Medicalrate = Convert.ToDecimal(txtDocument_Medical.Text);
                        _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal(txtDocument_Unemployed.Text);
                        _DetailInfo.Detail_Socialrate = Convert.ToDecimal(txtDocument_Social.Text);
                        _DetailInfo.Detail_Oldbasicfactor = 0;
                        _DetailInfo.Detail_Oldpositionfactor = 0;
                        _DetailInfo.Detail_Oldoverfactor = 0;
                        _DetailInfo.Detail_Oldjobfactor = 0;
                        _DetailInfo.Detail_Oldareafactor = 0;
                        _DetailInfo.Detail_Oldamount = 0;
                        if (_PDInfo.BasicSalary > 0)
                        {
                            _DetailInfo.Detail_Newamount = _PDInfo.BasicSalary;
                            _DetailInfo.Detail_Type = "ML";
                        }
                        else
                        {
                            _DetailInfo.Detail_Newbasicfactor = _PDInfo.BasicFactor;
                            _DetailInfo.Detail_Newpositionfactor = _PDInfo.PositionFactor;
                            _DetailInfo.Detail_Newoverfactor = _PDInfo.OverFactor;
                            _DetailInfo.Detail_Newjobfactor = _PDInfo.JobFactor;
                            _DetailInfo.Detail_Newareafactor = _PDInfo.AreaFactor;
                            _DetailInfo.Detail_Type = "HS";
                        }
                        _DetailInfo.Detail_Regioncode = "";
                        _DetailInfo.Detail_Hospitalcode = "";
                        _DetailInfo.Detail_Takecard = false;
                        _DetailInfo.Detail_Status = 2;
                        _DetailInfo.Detail_PositionName = !String.IsNullOrEmpty(_PDInfo.Job) ? _PDInfo.Job : _PositionInfo.Name;
                        _DetailInfo.Detail_Description = "";
                        if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate)
                            _DetailInfo.Detail_Totalmonth = 0;
                        else if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate && _DetailInfo.Detail_Todate == _ViewDate)
                            _DetailInfo.Detail_Totalmonth = 0;
                        else if ((_DetailInfo.Detail_Fromdate == _ViewDate || _DetailInfo.Detail_Todate == _ViewDate) && _DetailInfo.Detail_Fromdate < _DetailInfo.Detail_Todate)
                            _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate);
                        else
                            _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;

                        if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                        {
                            _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                        }
                    }
                }
                //
                LoadList();
            }
        }

        //Lấy dữ liệu TNN Vượt khung
        //Copy bản ghi phát sinh gần nhất
        //Tăng tỷ lệ  % VK lên 1
        private void btnTNKVK_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Sau khi lấy dữ liệu TNVK, bạn cần tiếp tục lấy dữ liệu TNN", "Cảnh báo lấy dữ liệu TNVK") != DialogResult.OK)
                return;

            string[] _ArrID = null;
            DataTable dtCanhBaoNghe = null;

            frmGetNewDataList_TNVK f = new frmGetNewDataList_TNVK(_listRole);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                _ArrID = f.SelectedID.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                dtCanhBaoNghe = f.dtDanhSachCanhBaoVK;
                bool DaTangKy = false;

                for (int i = 0; i < _ArrID.Length; i++)
                {
                    if (_ArrID[i].Length > 0)
                    {
                        //Insert Header:
                        //Tăng kỳ phát sinh lên 1
                        if (!DaTangKy)
                        {
                            HeaderForm2Info();
                            _HeaderInfo.Document_Period += 1;
                            _DocumentID = BhHeader_Controller.Instance().Header_Insert(_HeaderInfo);
                            DaTangKy = true;

                            //Tăng ds header
                            arg_HeaderID = Header_GetList();
                            Pager.Invalidate();
                        }

                        //Insert Detail:
                        _EmployeeID = Convert.ToInt32(_ArrID[i]);
                        _EmployeeInfo = _wcfEmployee.Employee_GetInfo(_EmployeeID);
                        _PDInfo = _wcfPositionDetal.PositionDetail_GetInfo(_EmployeeID);
                        _DetailID = 0;
                        _DetailInfo = new DetailInfo();
                        _DetailInfo.Detail_Documentid = _DocumentID;
                        _DetailInfo.Detail_Insbookno = _EmployeeInfo.SIBookNo;
                        _DetailInfo.Detail_Employeecode = _EmployeeInfo.Code;

                        //Từ tháng đến tháng
                        _DetailInfo.Detail_Fromdate = new DateTime(_HeaderInfo.Document_Year, _HeaderInfo.Document_Month, 1);
                        _DetailInfo.Detail_Todate = new DateTime(_HeaderInfo.Document_Year, _HeaderInfo.Document_Month, 1);

                        //PA
                        _DetailInfo.Detail_Instypecode = "DC";

                        //Tỷ lệ thu phải lấy theo bản ghi phát sinh trước đó, ko đc lấy theo txt
                        //_DetailInfo.MedicalRate = Convert.ToDecimal(txtDocument_Medical.Text);
                        //_DetailInfo.UnemployedRate = Convert.ToDecimal(txtDocument_Unemployed.Text);
                        //_DetailInfo.SocialRate = Convert.ToDecimal(txtDocument_Social.Text);

                        DataRow[] drArray = dtCanhBaoNghe.Select("Employee_ID = " + _ArrID[i]);
                        if (drArray != null)
                            if (drArray.Length == 1)
                            {
                                _DetailInfo.Detail_Socialrate = Convert.ToDecimal(drArray[0]["Premium_Rate"]);
                                _DetailInfo.Detail_Medicalrate = Convert.ToDecimal(drArray[0]["Premium_MedicalRate"]);
                                _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal(drArray[0]["Premium_UnemployedRate"]);
                            }

                        //
                        _DetailInfo.Detail_Oldbasicfactor = 0;
                        _DetailInfo.Detail_Oldpositionfactor = 0;
                        _DetailInfo.Detail_Oldoverfactor = 0;
                        _DetailInfo.Detail_Oldjobfactor = 0;
                        _DetailInfo.Detail_Oldareafactor = 0;
                        _DetailInfo.Detail_Oldamount = 0;

                        //Mức cũ
                        int OverFactorOldPercent = 0;
                        drArray = dtCanhBaoNghe.Select("Employee_ID = " + _ArrID[i]);
                        if (drArray != null)
                            if (drArray.Length == 1)
                            {
                                //Lấy dữ liệu mức cũ
                                _DetailInfo.Detail_Oldbasicfactor = Convert.ToDecimal(drArray[0]["Premium_BasicFactor"]);
                                _DetailInfo.Detail_Oldpositionfactor = Convert.ToDecimal(drArray[0]["Premium_PositionFactor"]);
                                _DetailInfo.Detail_Oldoverfactor = Convert.ToDecimal(drArray[0]["Premium_OverSeniorityFactor"]);
                                _DetailInfo.Detail_Oldjobfactor = Convert.ToDecimal(drArray[0]["Premium_SeniorityFactor"]);
                                _DetailInfo.Detail_Oldareafactor = Convert.ToDecimal(drArray[0]["Premium_AreaFactor"]);
                                _DetailInfo.Detail_Oldamount = Convert.ToDecimal(drArray[0]["Premium_Salary"]);
                                OverFactorOldPercent = Convert.ToInt32(drArray[0]["Detail_OverFactorPercent"]);
                                _DetailInfo.Detail_PositionName = drArray[0]["Detail_PositionName"].ToString();
                                //
                                _DetailInfo.Detail_Newjobfactor_Percent = Convert.ToInt32(drArray[0]["Detail_JobFactorPercent"]);
                            }

                        if (_PDInfo.BasicSalary > 0)
                        {
                            _DetailInfo.Detail_Newamount = _PDInfo.BasicSalary;
                            _DetailInfo.Detail_Type = InsuranceType.ML;
                        }
                        else
                        {
                            _DetailInfo.Detail_Newbasicfactor = _DetailInfo.Detail_Oldbasicfactor;
                            _DetailInfo.Detail_Newpositionfactor = _DetailInfo.Detail_Oldpositionfactor;

                            //Tính TNVK theo % + 1
                            _DetailInfo.Detail_Newoverfactor = ((OverFactorOldPercent + 1) * _DetailInfo.Detail_Newbasicfactor) / 100;
                            _DetailInfo.Detail_Newoverfactor_Percent = OverFactorOldPercent + 1;
                            _DetailInfo.Detail_Newjobfactor = _DetailInfo.Detail_Oldjobfactor;
                            _DetailInfo.Detail_Newareafactor = _DetailInfo.Detail_Oldareafactor;
                            _DetailInfo.Detail_Type = InsuranceType.HS;
                        }

                        _DetailInfo.Detail_Regioncode = "";
                        _DetailInfo.Detail_Hospitalcode = "";
                        _DetailInfo.Detail_Takecard = false;
                        _DetailInfo.Detail_Status = 2;
                        _DetailInfo.Detail_Description = "";

                        if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate)
                            _DetailInfo.Detail_Totalmonth = 0;
                        else if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate && _DetailInfo.Detail_Todate == _ViewDate)
                            _DetailInfo.Detail_Totalmonth = 0;
                        else if ((_DetailInfo.Detail_Fromdate == _ViewDate || _DetailInfo.Detail_Todate == _ViewDate) && _DetailInfo.Detail_Fromdate < _DetailInfo.Detail_Todate)
                            _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate);
                        else
                            _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;

                        if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                        {
                            _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                        }
                    }
                }

                if (_ArrID.Length > 0)
                    txtDocument_Period.Text = (Convert.ToInt32(txtDocument_Period.Text) + 1).ToString();
                //
                LoadList();

                MessageBox.Show("Đã hoàn thành lấy dữ liệu");
            }
        }

        //Lấy dữ liệu thâm niên nghề
        //Lấy bản ghi phát sinh gần nhất 
        //Tăng tỷ lệ % thâm niên nghề lên 1
        private void btnTNNghe_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn cần lấy dữ liệu TNVK trước khi lấy dữ liệu TNN", "Cảnh báo lấy dữ liệu TNN") != DialogResult.OK)
                return;

            string[] _ArrID = null;
            DataTable dtCanhBaoNghe = null;

            frmGetNewDataList_TNN f = new frmGetNewDataList_TNN(_listRole);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                _ArrID = f.SelectedID.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                dtCanhBaoNghe = f.dtDanhSachCanhBaoNghe;
                bool DaTangKy = false;

                for (int i = 0; i < _ArrID.Length; i++)
                {
                    if (_ArrID[i].Length > 0)
                    {
                        //Insert Header:
                        //Tăng kỳ phát sinh lên 1
                        if (!DaTangKy)
                        {
                            HeaderForm2Info();
                            _HeaderInfo.Document_Period += 1;
                            _DocumentID = BhHeader_Controller.Instance().Header_Insert(_HeaderInfo);
                            DaTangKy = true;
                            //
                            //Tăng ds header
                            arg_HeaderID = Header_GetList();
                            Pager.Invalidate();
                        }

                        //Insert Detail:
                        _EmployeeID = Convert.ToInt32(_ArrID[i]);
                        _EmployeeInfo = _wcfEmployee.Employee_GetInfo(_EmployeeID);
                        _PDInfo = _wcfPositionDetal.PositionDetail_GetInfo(_EmployeeID);
                        _DetailID = 0;
                        _DetailInfo = new DetailInfo();
                        _DetailInfo.Detail_Documentid = _DocumentID;
                        _DetailInfo.Detail_Insbookno = _EmployeeInfo.SIBookNo;
                        _DetailInfo.Detail_Employeecode = _EmployeeInfo.Code;

                        //Từ tháng đến tháng
                        _DetailInfo.Detail_Fromdate = new DateTime(_HeaderInfo.Document_Year, _HeaderInfo.Document_Month, 1);
                        _DetailInfo.Detail_Todate = new DateTime(_HeaderInfo.Document_Year, _HeaderInfo.Document_Month, 1);

                        //PA
                        _DetailInfo.Detail_Instypecode = "DC";
                        _DetailInfo.Detail_Medicalrate = Convert.ToDecimal(txtDocument_Medical.Text);
                        _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal(txtDocument_Unemployed.Text);
                        _DetailInfo.Detail_Socialrate = Convert.ToDecimal(txtDocument_Social.Text);


                        //
                        DataRow[] drArray = dtCanhBaoNghe.Select("Employee_ID = " + _ArrID[i]);
                        if (drArray != null)
                            if (drArray.Length == 1)
                            {
                                _DetailInfo.Detail_Socialrate = Convert.ToDecimal(drArray[0]["Premium_Rate"]);
                                _DetailInfo.Detail_Medicalrate = Convert.ToDecimal(drArray[0]["Premium_MedicalRate"]);
                                _DetailInfo.Detail_Unemployedrate = Convert.ToDecimal(drArray[0]["Premium_UnemployedRate"]);

                            }

                        //
                        _DetailInfo.Detail_Oldbasicfactor = 0;
                        _DetailInfo.Detail_Oldpositionfactor = 0;
                        _DetailInfo.Detail_Oldoverfactor = 0;
                        _DetailInfo.Detail_Oldjobfactor = 0;
                        _DetailInfo.Detail_Oldareafactor = 0;
                        _DetailInfo.Detail_Oldamount = 0;



                        //Mức cũ
                        int JobFactorOldPercent = 0;
                        drArray = dtCanhBaoNghe.Select("Employee_ID = " + _ArrID[i]);
                        if (drArray != null)
                            if (drArray.Length == 1)
                            {
                                //Lấy dữ liệu mức cũ
                                _DetailInfo.Detail_Oldbasicfactor = Convert.ToDecimal(drArray[0]["Premium_BasicFactor"]);
                                _DetailInfo.Detail_Oldpositionfactor = Convert.ToDecimal(drArray[0]["Premium_PositionFactor"]);
                                _DetailInfo.Detail_Oldoverfactor = Convert.ToDecimal(drArray[0]["Premium_OverSeniorityFactor"]);
                                _DetailInfo.Detail_Oldjobfactor = Convert.ToDecimal(drArray[0]["Premium_SeniorityFactor"]);
                                _DetailInfo.Detail_Oldareafactor = Convert.ToDecimal(drArray[0]["Premium_AreaFactor"]);
                                _DetailInfo.Detail_Oldamount = Convert.ToDecimal(drArray[0]["Premium_Salary"]);
                                JobFactorOldPercent = Convert.ToInt32(drArray[0]["Detail_JobFactorPercent"]);
                                _DetailInfo.Detail_Newoverfactor_Percent = Convert.ToInt32(drArray[0]["Detail_OverFactorPercent"]);
                                _DetailInfo.Detail_PositionName = drArray[0]["Detail_PositionName"].ToString();
                            }

                        if (_PDInfo.BasicSalary > 0)
                        {
                            _DetailInfo.Detail_Newamount = _PDInfo.BasicSalary;
                            _DetailInfo.Detail_Type = "ML";
                        }
                        else
                        {
                            _DetailInfo.Detail_Newbasicfactor = _DetailInfo.Detail_Oldbasicfactor;
                            _DetailInfo.Detail_Newpositionfactor = _DetailInfo.Detail_Oldpositionfactor;
                            _DetailInfo.Detail_Newoverfactor = _DetailInfo.Detail_Oldoverfactor;
                            _DetailInfo.Detail_Newareafactor = _DetailInfo.Detail_Oldareafactor;
                            _DetailInfo.Detail_Type = "HS";

                            //Tính TNN theo % + 1
                            _DetailInfo.Detail_Newjobfactor = ((JobFactorOldPercent + 1) * (_DetailInfo.Detail_Oldbasicfactor + _DetailInfo.Detail_Oldpositionfactor + _DetailInfo.Detail_Oldoverfactor)) / 100;
                            _DetailInfo.Detail_Newjobfactor_Percent = JobFactorOldPercent + 1;
                        }

                        _DetailInfo.Detail_Regioncode = "";
                        _DetailInfo.Detail_Hospitalcode = "";
                        _DetailInfo.Detail_Takecard = false;
                        _DetailInfo.Detail_Status = 2;
                        _DetailInfo.Detail_Description = "";//khi cần, chuyên viên sẽ nhập

                        if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate)
                            _DetailInfo.Detail_Totalmonth = 0;
                        else if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate && _DetailInfo.Detail_Todate == _ViewDate)
                            _DetailInfo.Detail_Totalmonth = 0;
                        else if ((_DetailInfo.Detail_Fromdate == _ViewDate || _DetailInfo.Detail_Todate == _ViewDate) && _DetailInfo.Detail_Fromdate < _DetailInfo.Detail_Todate)
                            _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate);
                        else
                            _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;

                        if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                        {
                            _DetailID = Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                        }
                    }
                }

                if (_ArrID.Length > 0)
                {
                    txtDocument_Period.Text = (Convert.ToInt32(txtDocument_Period.Text) + 1).ToString();

                    Pager.TotalRow += 1;
                }
                //
                LoadList();
                //

                //
                MessageBox.Show("Đã hoàn thành lấy dữ liệu");
            }
        }

        //Lấy danh sách TS
        //Lấy danh sách thai sản đã nghỉ đủ tháng, cần ON lại
        //Mức lương lấy theo trước lúc nghỉ, được phép sửa
        private void mnuGet_TS_Click(object sender, EventArgs e)
        {
            //Lưu dữ liệu kỳ hiện tại
            SaveHeader();
            //
            frmGetNewDataList_TS f = new frmGetNewDataList_TS(_HeaderInfo, txtDocument_Medical.GetValue<decimal>()
                    , txtDocument_Unemployed.GetValue<decimal>()
                    , txtDocument_Social.GetValue<decimal>()
                    , _ViewDate);
            //
            if (f.Show_Form(this) == DialogResult.OK)
            {
                FormGlobals.App_ProgressShow(delegate()
                {
                    LoadList();
                }, "Lấy dữ liệu phát sinh trong kỳ");
            }
        }

        //Lấy quá trình tước đây
        void PremiumInfo()
        {
            _PremiumInfo = new PremiumInfo();
            _PremiumInfo.EmployeeID = _EmployeeID;
            _PremiumInfo.SIBookNo = _DetailInfo.Detail_Insbookno;
            _PremiumInfo.Type = _Type;
            _PremiumInfo.WorkUnit = Program.strBranchCode;
            _PremiumInfo.WorkName = Program.strBranch;
            _PremiumInfo.FromDate = _DetailInfo.Detail_Fromdate;
            _PremiumInfo.ToDate = _DetailInfo.Detail_Todate;
            _PremiumInfo.MonthNo = UISetting.GetMonth(_PremiumInfo.FromDate, _PremiumInfo.ToDate);
            _PremiumInfo.Job = "";
            _PremiumInfo.InsTypeCode = _DetailInfo.Detail_Instypecode;
            _PremiumInfo.BasicSalary = UISetting.GetDecimalNo(txtDocument_Basicsalary.Text);
            _PremiumInfo.Salary = _DetailInfo.Detail_Newamount;
            _PremiumInfo.BasicFactor = _DetailInfo.Detail_Newbasicfactor;
            _PremiumInfo.PositionFactor = _DetailInfo.Detail_Newpositionfactor;
            _PremiumInfo.SeniorityFactor = _DetailInfo.Detail_Newjobfactor;
            _PremiumInfo.AreaFactor = _DetailInfo.Detail_Newareafactor;
            _PremiumInfo.OverSeniorityFactor = _DetailInfo.Detail_Newoverfactor;
            _PremiumInfo.Description = "";
            _PremiumInfo.DateVal = _DetailInfo.Detail_Fromdate;
        }

        //Thu thẻ => không được sửa số tháng
        private void chkTakeCard_CheckedChanged(object sender, EventArgs e)
        {
            FormGlobals.Control_SetViewOnly(cbxDetail_Takecard.Checked, txtCountMonth);
            //txtCountMonth.Enabled = !cbxDetail_Takecard.Checked;
        }

        //Tính toán fill các giá trị khi nhập Phương án
        //Khi thay đổi phương án
        // - Gán lại các giá trị tỷ lệ thu,
        // - Lấy các giá trị của phát sinh tương ứng
        private void ThayDoiPhuongAn()
        {
            FormGlobals.Control_SetViewOnly(false
                , txtDetail_Socialrate
                , txtDetail_Medicalrate
                , txtDetail_Unemployedrate
                //
                , txtDetail_PositionName
                );
            //
            FormGlobals.Control_SetRequired(txtDetail_PositionName, true);
            //
            if (txtDetail_Insbookno.IsEmpty() || txtDetail_Instypecode.IsEmpty())
                return;

            //
            DateTime _date1 = DateTime.MinValue;
            DateTime _date2 = DateTime.MinValue;

            string _InsType = txtDetail_Instypecode.Text.ToUpper();

            if (!CheckQTBHTmp(dtQTBHXH, "XH"))
            {
                txtDetail_Todate.SetFocus_SelectAll();
                return;
            }
            if (_InsType == "TT" || _InsType == "TU")
            {
                //13.09: Anh Tuy: Bảo mở khóa
                //.Lý do: nhiều trường hợp TT/TU của năm trước

                //if ((txtYear.Text != txtFromDate.Text.Substring(3, 4) || txtYear.Text != txtToDate.Text.Substring(3, 4)))
                //{
                //    MessageBox.Show("Phương án TT/TU chỉ được sử dụng trong năm " + txtYear.Text);
                //    txtInsTypeCode.Text = "";
                //    txtFromDate.Focus();
                //    txtFromDate.SelectAll();
                //    return;
                //}
                //if (dtQTBHXH.Rows.Count > 0)
                //{
                //    MessageBox.Show("Số sổ này chưa báo giảm, không sử dụng được phương án TT/TU");
                //    AlreadyTxtInstyCodeLeave = true;
                //    txtInsTypeCode.Focus();
                //    txtInsTypeCode.SelectAll();
                //    return;
                //}

                dtQTBHXH = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text, 0, DateTime.MinValue, DateTime.MaxValue, 0).Tables[0];

                //06/05: Lấy thằng mới nhất trong quá trình, ko phải thằng cũ nhất
                //for(int i = 0; i < dtQTBHXH.Rows.Count-1 ; i++)
                //{
                //    dtQTBHXH.Rows[i].Delete();
                //}
                for (int i = dtQTBHXH.Rows.Count - 1; i > 0; i--)
                    dtQTBHXH.Rows[i].Delete();
                dtQTBHXH.AcceptChanges();
            }

            bool IsQuited = false;

            DataTable dtTmp = LocalDB.Employee_GetListByParameter(txtDetail_Insbookno.Text);
            if (dtTmp.Rows.Count == 1)
                IsQuited = Convert.ToBoolean(dtTmp.Rows[0]["Employee_IsQuited"]);

            if (IsQuited && _InsType != "ON")
            {
                //MessageBox.Show("Nhân viên này đã nghỉ việc, chỉ được thực hiện phương án ON");

                //FormGlobals.Message_Warning("Nhân viên này đã nghỉ việc, chỉ được thực hiện phương án ON");
                Program.taskbarNotifier.Show(UIParamater.TitleProject, "Nhân viên này đã nghỉ việc, chỉ được thực hiện phương án ON", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);

                txtDetail_Instypecode.Text = "ON";
                txtDetail_Instypecode.SetFocus_SelectAll();
                return;
            }

            //Check các PA
            switch (_InsType)
            {
                //Phương án giảm, hỏi có thu thẻ không
                case "GC":
                case "GD":
                case "GH":
                case "OF":
                case "KL":
                    
                    
                    if (_DetailID == 0 && _toDate == _ViewDate)
                    {
                        if (MessageBox.Show("Bạn có muốn trả thẻ không?", UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            _TakeCard = false;
                            cbxDetail_Takecard.Checked = false;
                            _date1 = UISetting.GetDate(txtDetail_Todate.Text);
                            _date2 = UISetting.GetDate("01/12/" + txtDocument_Year.Text.Replace(",", "").Replace(".", ""));
                            txtCountMonth.Text = (UISetting.GetMonth(_date1, _date2) + 1).ToString();

                            //FormGlobals.Control_SetViewOnly(false, txtCountMonth);
                            //txtCountMonth.Enabled = true;
                            txtCountMonth.Focus();
                            //txtInsTypeCode.Focus();

                        }
                        else//Không thu thẻ thì thu số tháng đánh vào (mặc định đến thang 12)
                        {
                            cbxDetail_Takecard.Checked = true;
                            _TakeCard = true;
                        }
                    }
                    //txtDetail_Medicalrate.ReadOnly = true;
                    //txtDetail_Medicalrate.BackColor = Color.White;

                    break;

                //case "AD":
                //case "TC":
                //case "TD":
                //case "TM":
                //Phương án ON: đi làm lại, phải có quá trình đóng thuộc đơn vị, khi ON sẽ lấy mức lương gần nhất Fill vào mức mới, cho sửa
                case "ON":
                    DateTime _DateFrom = DateTime.MinValue;
                    //GỌi quá trình, lấy bản ghi mới nhất thứ 2
                    //chi ho tro truoc khi ON tham gia dong cung loai HS, hoac ML
                    //ON khac loai dong thi ko lay duoc
                    //Truoc phuong an ON thì luong/he so luon phai = 0 là đúng
                    _fromDate = DateTime.MinValue ;//txtDetail_Fromdate.GetValue<DateTime>();
                    _toDate = txtDetail_Todate.GetValue<DateTime>();
                    DataTable dtPD = _wcfPremium.Premium_QTBH(Program.strBranchCode, txtDetail_Insbookno.Text.Trim(), 0, _fromDate, _toDate, _DocumentID).Tables[0];

                    int rowCount = dtPD.Rows.Count;
                    if (rowCount >= 2 && Globals.DB_GetString(dtPD.Rows[rowCount - 1]["loaips"]) == _Type)
                    {
                        txtNewAmount.Text = Convert.ToDecimal(dtPD.Rows[rowCount - 2]["Premium_Salary"]).ToString("#,##0");
                        txtDetail_Newbasicfactor.Text = Convert.ToDecimal(dtPD.Rows[rowCount - 2]["Premium_BasicFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Newpositionfactor.Text = Convert.ToDecimal(dtPD.Rows[rowCount - 2]["Premium_PositionFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Newoverfactor.Text = Convert.ToDecimal(dtPD.Rows[rowCount - 2]["Premium_OverSeniorityFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Newjobfactor.Text = Convert.ToDecimal(dtPD.Rows[rowCount - 2]["Premium_SeniorityFactor"]).ToString(UIParamater.Cham3So);
                        txtDetail_Newareafactor.Text = Convert.ToDecimal(dtPD.Rows[rowCount - 2]["Premium_AreaFactor"]).ToString(UIParamater.Cham3So);
                        txtOldAmount.Text = "0";
                        txtDetail_Oldbasicfactor.Text = "0";
                        txtDetail_Oldpositionfactor.Text = "0";
                        txtDetail_Oldoverfactor.Text = "0";
                        txtDetail_Oldjobfactor.Text = "0";
                        txtDetail_Oldareafactor.Text = "0";
                    }
                    else
                    {
                        txtOldAmount.Text = "0";
                        txtDetail_Oldbasicfactor.Text = "0";
                        txtDetail_Oldpositionfactor.Text = "0";
                        txtDetail_Oldoverfactor.Text = "0";
                        txtDetail_Oldjobfactor.Text = "0";
                        txtDetail_Oldareafactor.Text = "0";
                    }

                    //_EmployeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(txtDetail_Insbookno.Text.Trim());
                    //if (_EmployeeInfo != null)
                    //{
                    //     dtPD = new DataTable();
                    //    int n = 0;
                    //    dtPD = Detail_Controller.Instance().Detail_GetBySIBookNo(txtDetail_Insbookno.Text, Program.strBranchCode, _fromDate).Tables[0];
                    //    n = dtPD.Rows.Count;
                    //    if (n > 0)
                    //    {
                    //        if (_DetailID == 0)//Neu tao moi thi lay muc luong cu da co:
                    //        {
                    //            txtNewAmount.Text = Convert.ToDecimal(dtPD.Rows[0]["Detail_NewAmount"]).ToString("#,##0");
                    //            txtDetail_Newbasicfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["Detail_NewBasicFactor"]).ToString(UIParamater.Cham3So);
                    //            txtDetail_Newpositionfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["Detail_NewPositionFactor"]).ToString(UIParamater.Cham3So);
                    //            txtDetail_Newoverfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["Detail_NewOverFactor"]).ToString(UIParamater.Cham3So);
                    //            txtDetail_Newjobfactor.Text = Convert.ToDecimal(dtPD.Rows[0]["Detail_NewJobFactor"]).ToString(UIParamater.Cham3So);
                    //            txtDetail_Newareafactor.Text = Convert.ToDecimal(dtPD.Rows[0]["Detail_NewAreaFactor"]).ToString(UIParamater.Cham3So);
                    //            txtOldAmount.Text = "0";
                    //            txtDetail_Oldbasicfactor.Text = "0";
                    //            txtDetail_Oldpositionfactor.Text = "0";
                    //            txtDetail_Oldoverfactor.Text = "0";
                    //            txtDetail_Oldjobfactor.Text = "0";
                    //            txtDetail_Oldareafactor.Text = "0";
                    //        }
                    //    }
                    //    else
                    //    {
                    //        txtOldAmount.Text = "0";
                    //        txtDetail_Oldbasicfactor.Text = "0";
                    //        txtDetail_Oldpositionfactor.Text = "0";
                    //        txtDetail_Oldoverfactor.Text = "0";
                    //        txtDetail_Oldjobfactor.Text = "0";
                    //        txtDetail_Oldareafactor.Text = "0";
                    //    }
                    //}
                    break;
                //case "TT":
                default:
                    txtDetail_Totalmonth.Text = (CountMonth(UISetting.GetDate(txtDetail_Fromdate.Text), UISetting.GetDate(txtDetail_Todate.Text), _ViewDate, _InsType)).ToString();
                    break;


            }
            //
            //FormGlobals.Control_SetViewOnly(true, txtDetail_Unemployedrate);

            switch (_InsType)
            {
                //CLEAR %BHXH, %BHTN;
                case "TU":
                    FillTyLeThu(false, true, false);
                    FillHSML("MC");
                    //
                    //FormGlobals.Control_SetViewOnly(true, txtDetail_Unemployedrate, txtDetail_Socialrate);
                    txtDetail_Newbasicfactor.SetFocus_SelectAll();
                    break;
                case "TT":
                    FillTyLeThu(false, true, false);
                    FillHSML("MM");
                    //
                    //FormGlobals.Control_SetViewOnly(true, txtDetail_Unemployedrate, txtDetail_Socialrate, txtDetail_Unemployedrate);
                    txtDetail_Newbasicfactor.SetFocus_SelectAll();
                    break;
                case "TS":
                case "TM":
                case "AD":
                //case "ON":
                case "TC":
                case "TD":
                case "DC":
                    FillTyLeThu(true, true, true);
                    FillHSML("MC");
                    //
                    txtDetail_Unemployedrate.SetFocus_SelectAll();
                    break;
                case "SB":
                    FillTyLeThu(true, false, true);
                    FillHSML("MC");
                    //
                    txtDetail_Unemployedrate.SetFocus_SelectAll();
                    break;
                case "TN":
                case "DN":
                    if (dtQTBHTN.Rows.Count > 0)
                    {
                        MessageBox.Show("Thời gian này đã tham gia BHTN, dùng phương án DC để điều chỉnh");
                        txtDetail_Instypecode.Text = "";
                        txtDetail_Instypecode.SetFocus_SelectAll();
                    }
                    else if (dtQTBHXH.Rows.Count != 0)
                    {
                        FillTyLeThu(false, false, true);
                        FillHSML("MM");
                        //
                        //FormGlobals.Control_SetViewOnly(true, txtDetail_Unemployedrate);
                        txtDetail_Newbasicfactor.SetFocus_SelectAll();
                    }
                    else
                    {
                        MessageBox.Show("Thời gian này chưa tham gia BHXH");
                        txtDetail_Instypecode.Text = "";
                        txtDetail_Instypecode.SetFocus_SelectAll();
                    }
                    //
                    //FormGlobals.Control_SetViewOnly(true, txtDetail_Socialrate, txtDetail_Medicalrate);

                    break;
                case "GN":
                    if (dtQTBHTN.Rows.Count != 0)
                    {
                        FillTyLeThu(false, false, true);
                        FillHSML("MC");
                        //
                        //FormGlobals.Control_SetViewOnly(true, txtDetail_Unemployedrate);
                        txtDetail_Newbasicfactor.SetFocus_SelectAll();
                    }
                    else
                    {
                        MessageBox.Show("Thời gian này chưa tham gia BHTN, không báo giảm TN được");
                        txtDetail_Instypecode.Text = "";
                        txtDetail_Instypecode.Focus();
                    }
                    //
                    //FormGlobals.Control_SetViewOnly(true, txtDetail_Socialrate, txtDetail_Medicalrate);
                    break;
                case "GH":
                case "GC":
                case "GD":
                case "OF":
                case "KL":
                    FillTyLeThu(true, false, true);
                    FillHSML("MC");
                    //
                    txtDetail_Unemployedrate.SetFocus_SelectAll();
                    break;
                case "CD":
                    FillTyLeThu(false, false, false);
                    FillHSML("0"); //gán tất cả về 0
                    //
                    //FormGlobals.Control_SetViewOnly(true, txtDetail_Unemployedrate);
                    txtDetail_PositionName.SetFocus_SelectAll();
                    break;
            }

            //Xét ẩn hiện các ô nhập liệu tương ứng với các Phương Án nhập
            //Các phương án giảm, ko nhập chức danh, khóa các khung nhập liệu
            if ("TN/DN/GH/GC/GD/OF/TS/KL".Contains(_InsType)) // khóa cả cũ và mới
            {
                FormGlobals.Control_SetRequired(txtDetail_PositionName, false);
                FormGlobals.Control_SetViewOnly(txtDetail_PositionName, true);
                //
                FormGlobals.Control_SetViewOnly(true, grbMucCu, grbMucMoi, grbMucCuTien,grbMucMoiTien);
            }
            else if ("CD".Contains(_InsType)) //Khóa cả cũ và mới
            {
                FormGlobals.Control_SetRequired(txtDetail_PositionName, true);
                FormGlobals.Control_SetViewOnly(txtDetail_PositionName, false);
                //
                FormGlobals.Control_SetViewOnly(true, grbMucCu, grbMucMoi, grbMucCuTien, grbMucMoiTien);
            }
            else if ("DC".Contains(_InsType)) //Khóa cũ, nhập mới
            {
                FormGlobals.Control_SetRequired(txtDetail_PositionName, true);
                FormGlobals.Control_SetViewOnly(txtDetail_PositionName, false);
                //
                FormGlobals.Control_SetViewOnly(true, grbMucCu, grbMucCuTien);
                FormGlobals.Control_SetViewOnly(false, grbMucMoi, grbMucMoiTien);
            }
            else if("TM/AD/ON/TC/TD".Contains(_InsType)) //khóa cũ, nhập mới
            {
                FormGlobals.Control_SetRequired(txtDetail_PositionName, true);
                FormGlobals.Control_SetViewOnly(txtDetail_PositionName, false);
                //
                FormGlobals.Control_SetViewOnly(true, grbMucCu, grbMucCuTien);
                FormGlobals.Control_SetViewOnly(false, grbMucMoi, grbMucMoiTien);
            }

            ////-Xét ẩn hiện các ô nhập mức mới, mức cũ theo PA
            //if (dtQTBHXH.Rows.Count > 0 || "TM/ON/TT".Contains(txtDetail_Instypecode.Text))
            //{
            //    if (_Type == "HS")
            //    {
            //        FormGlobals.Control_SetViewOnly(true, grbMucCu);
            //        FormGlobals.Control_SetViewOnly(false, grbMucMoi);
            //    }
            //    else if (_Type == "ML")
            //    {
            //        FormGlobals.Control_SetViewOnly(true, txtOldAmount);
            //        FormGlobals.Control_SetViewOnly(false, txtNewAmount);
            //    }
            //}
            //else
            //{
            //    if (_Type == "HS")
            //    {
            //        FormGlobals.Control_SetViewOnly(false, grbMucCu);
            //        FormGlobals.Control_SetViewOnly(true, grbMucMoi);
            //    }
            //    else if (_Type == "ML")
            //    {
            //        FormGlobals.Control_SetViewOnly(false, txtOldAmount);
            //        FormGlobals.Control_SetViewOnly(true, txtNewAmount);
            //    }
            //}

            //if (("TN,DN,TT,TU,GH,GC,GD,OF,TS").IndexOf(txtInsTypeCode.Text) >= 0)
            //13.09: TT/TU được phép nhập mức lương mới
            //- Trường hợp nâng lương cơ bản. Truy thu theo mức lương mới, hiệu lực của thẻ

            //if (("TN/DN/GH/GC/GD/OF/TS").Contains(txtDetail_Instypecode.Text))
            //{
            //    FormGlobals.Control_SetViewOnly(true, grbMucMoi);
            //    FormGlobals.Control_SetViewOnly(false, grbMucCu);
            //}
        }

        //Fill dữ liệu tỷ lệ thu
        public void FillTyLeThu(bool BHXH, bool BHYT, bool BHTN)
        {
            FormGlobals.TextBox_SetValue(txtDetail_Medicalrate, BHYT ? _RateInfo.Rate_Medical : 0);
            FormGlobals.TextBox_SetValue(txtDetail_Socialrate, BHXH ? _RateInfo.Rate_Social : 0);
            //
            decimal dUnemployed = 0;
            if (BHTN)
            {
                decimal sumofhsml = 0;
                if (dtQTBHXH.Rows.Count > 0)
                    sumofhsml = (decimal)dtQTBHXH.Rows[0]["Premium_Salary"] + (decimal)dtQTBHXH.Rows[0]["Premium_BasicFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_PositionFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_SeniorityFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_OverSeniorityFactor"] + (decimal)dtQTBHXH.Rows[0]["Premium_AreaFactor"];

                if (!(dtQTBHTN.Rows.Count == 0 && ("TN,GN,DN").IndexOf(txtDetail_Instypecode.Text) < 0 && sumofhsml != 0))
                {
                    dUnemployed = _RateInfo.Rate_Unemployed;
                }
            }
            FormGlobals.TextBox_SetValue(dUnemployed, txtDetail_Unemployedrate);
        }


        //Fill các giá trị đóng mặc định theo PA. tùy từng PA mà được đóng mở Mức cũ, mức mới
        //Chỉ fill giữ liệu, ko bao gồm khóa khoáy ô nhập
        public void FillHSML(string sMucLuong)
        {
            DataRow dr = dtQTBHXH.Rows.Count == 1 ? dtQTBHXH.Rows[0] : null;
            //
            switch (sMucLuong)
            {
                case MucLuong.MUC_CU:
                    switch (_Type)
                    {
                        case InsuranceType.HS:
                            //Gán giá trị tất cả default về 0
                            FormGlobals.TextBox_SetValue(0,
                                txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor_Percent, txtDetail_Oldjobfactor, txtDetail_Oldareafactor,
                                txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor_Percent, txtDetail_Newoverfactor, txtDetail_Newjobfactor_Percent, txtDetail_Newjobfactor, txtDetail_Newareafactor,
                                txtDetail_Oldoverfactor_Percent,
                                txtDetail_Oldjobfactor_Percent
                                );
                            //
                            if (dr!=null)
                            {
                                txtDetail_Oldbasicfactor.Text = dr.GetValue<decimal>("Premium_BasicFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);  
                                txtDetail_Oldpositionfactor.Text = dr.GetValue<decimal>("Premium_PositionFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);  
                                txtDetail_Oldoverfactor.Text = dr.GetValue<decimal>("Premium_OverSeniorityFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT); 
                                txtDetail_Oldjobfactor.Text = dr.GetValue<decimal>("Premium_SeniorityFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT); 
                                txtDetail_Oldareafactor.Text = dr.GetValue<decimal>("Premium_AreaFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);

                                //Tính % của mức cũ khi lấy thông tin từ info=> form
                                decimal OldBasicFactor = txtDetail_Oldbasicfactor.GetValue<decimal>();
                                decimal OldPosionFactor = txtDetail_Oldpositionfactor.GetValue<decimal>();
                                decimal OldOverFactor = txtDetail_Oldoverfactor.GetValue<decimal>();
                                decimal OldJobFactor = txtDetail_Oldjobfactor.GetValue<decimal>();
                                //
                                if (OldBasicFactor != 0)
                                {
                                    decimal OldOverFactor_Percent = (OldOverFactor * 100 / OldBasicFactor);
                                    txtDetail_Oldoverfactor_Percent.SetText(Math.Round(OldOverFactor_Percent));
                                }
                                if (OldBasicFactor + OldPosionFactor + OldOverFactor != 0)
                                {
                                    decimal OldJobFactor_Percnet = (OldJobFactor * 100 / (OldBasicFactor + OldPosionFactor + OldOverFactor));
                                    txtDetail_Oldjobfactor_Percent.SetText(Math.Round(OldJobFactor_Percnet));
                                }

                                //Cảnh báo những ô có vượt khung,  nghề, chức vụ 
                                if (OldPosionFactor != 0)
                                    txtDetail_Oldpositionfactor.ForeColor = Color.Red;
                                if (OldOverFactor != 0)
                                    txtDetail_Oldoverfactor.ForeColor = Color.Red;
                                if (OldJobFactor != 0)
                                    txtDetail_Oldjobfactor.ForeColor = Color.Red;
                            }
                            break;
                        case InsuranceType.ML:
                            FormGlobals.TextBox_SetValue(0,txtOldAmount,txtNewAmount);
                            //
                            if (dtQTBHXH.Rows.Count == 1)
                            {
                                txtOldAmount.Text = GetDecimalValueUtil(dtQTBHXH.Rows[0]["Premium_Salary"], UIParamater.Phay2So);
                            }
                            break;
                    }

                    break;
                case MucLuong.MUC_MOI:
                    switch (_Type)
                    {
                        case InsuranceType.HS:
                            //Gán giá trị default về 0
                            FormGlobals.TextBox_SetValue(0,
                                txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor_Percent, txtDetail_Oldjobfactor, txtDetail_Oldareafactor,
                                txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor_Percent, txtDetail_Newoverfactor, txtDetail_Newjobfactor_Percent, txtDetail_Newjobfactor, txtDetail_Newareafactor,
                                txtDetail_Newoverfactor_Percent,
                                txtDetail_Newjobfactor_Percent
                                );

                            //
                            if (dr!=null)
                            {
                                txtDetail_Newbasicfactor.Text = dr.GetValue<decimal>("Premium_BasicFactor",0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                                txtDetail_Newpositionfactor.Text = dr.GetValue<decimal>("Premium_PositionFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                                txtDetail_Newoverfactor.Text = dr.GetValue<decimal>("Premium_OverSeniorityFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                                txtDetail_Newjobfactor.Text = dr.GetValue<decimal>("Premium_SeniorityFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT);
                                txtDetail_Newareafactor.Text = dr.GetValue<decimal>("Premium_AreaFactor", 0).ToString(Globals.CS_DISPLAY_RATE_FORMAT); 

                                //Tính % của mức cũ khi lấy thông tin từ info=> form
                                decimal NewBasicFactor = txtDetail_Newbasicfactor.GetValue<decimal>();
                                decimal NewPosionFactor = txtDetail_Newpositionfactor.GetValue<decimal>();
                                decimal NewOverFactor = txtDetail_Newoverfactor.GetValue<decimal>();
                                decimal NewJobFactor = txtDetail_Newjobfactor.GetValue<decimal>();
                                //
                                if (NewOverFactor != 0)
                                {
                                    decimal NewOverFactor_Percent = (NewOverFactor * 100 / NewBasicFactor);
                                    txtDetail_Newoverfactor_Percent.SetText(Math.Round(NewOverFactor_Percent));
                                }
                                if (NewJobFactor != 0)
                                {
                                    decimal NewJobFactor_Percnet = (NewJobFactor * 100 / (NewBasicFactor + NewPosionFactor + NewOverFactor));
                                    txtDetail_Newjobfactor_Percent.SetText(Math.Round(NewJobFactor_Percnet));
                                }
                            }
                            break;
                        case InsuranceType.ML:
                            FormGlobals.TextBox_SetValue(0, txtOldAmount, txtNewAmount);
                            if (dr!=null)
                                txtNewAmount.Text = dr.GetValue<decimal>("Premium_Salary",0).ToString(UIParamater.Phay2So);
                            break;
                    }
                    break;
                default:
                    //Gán giá trị tất cả các ô nhập của mức cũ, mức mới về 0
                    FormGlobals.TextBox_SetValue(0,
                        txtDetail_Oldbasicfactor, txtDetail_Oldpositionfactor, txtDetail_Oldoverfactor_Percent, txtDetail_Oldoverfactor, txtDetail_Oldjobfactor_Percent, txtDetail_Oldjobfactor, txtDetail_Oldareafactor,
                        txtDetail_Newbasicfactor, txtDetail_Newpositionfactor, txtDetail_Newoverfactor_Percent, txtDetail_Newoverfactor, txtDetail_Newjobfactor_Percent, txtDetail_Newjobfactor, txtDetail_Newareafactor,
                        txtDetail_Oldoverfactor_Percent,
                        txtDetail_Oldjobfactor_Percent,
                        txtDetail_Newoverfactor_Percent,
                        txtDetail_Newjobfactor_Percent,
                        txtOldAmount, txtNewAmount
                    );

                    break;
            }

            //hiepdh: KHóa ô nhập % TNN và TNVK trong trường hợp nhân sự này đc tick ko tính TNN và TNVK bên nhân sự
            KhongTinhTNNvsTNVK(txtDetail_Insbookno.Text);
        }

        //Khóa nút gọi TNN và TNVK tự động nếu tick ko tham gia đóng bên nhân sự
        private void KhongTinhTNNvsTNVK(string SoSoBHXH)
        {
            EmployeeInfo eInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(SoSoBHXH);
            if (eInfo != null)
            {
                FormGlobals.Control_SetViewOnly(eInfo.UnJobFactor, txtDetail_Newjobfactor, txtDetail_Newjobfactor_Percent);
                FormGlobals.Control_SetViewOnly(eInfo.UnOverFactor, txtDetail_Newoverfactor, txtDetail_Newoverfactor_Percent);

                // Set up the ToolTip text for the Button and Checkbox.
                if (eInfo.UnJobFactor)
                {
                    toolTip1.SetToolTip(txtDetail_Newjobfactor, "TNN bị khóa do lao động này được đánh dấu không tham gia TNN bên nhân sự");
                    toolTip1.SetToolTip(txtDetail_Newjobfactor_Percent, "TNN bị khóa do lao động này được đánh dấu không tham gia TNN bên nhân sự");
                }
                if (eInfo.UnOverFactor)
                {
                    toolTip1.SetToolTip(txtDetail_Newoverfactor, "TNKVK bị khóa do lao động này được đánh dấu không tham gia TNVK bên nhân sự");
                    toolTip1.SetToolTip(txtDetail_Newoverfactor_Percent, "TNVK bị khóa do lao động này được đánh dấu không tham gia TNVK bên nhân sự");
                }
            }
        }


        //Xóa cả kỳ phát sinh
        private void btnDelAll_Click(object sender, EventArgs e)
        {
            if (!_listRole.Delete)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (_DocumentID > 0 && MessageBox.Show("Bạn có chắc chắn muốn xóa hết các phát sinh trong kỳ này không!", UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int curPeriod = txtDocument_Period.GetValue<int>();
                //
                Detail_Controller.Instance().Detail_Delete(0, _DocumentID);
                BhHeader_Controller.Instance().Header_DeleteByPeriod(Program.strBranchCode, Convert.ToInt32(txtDocument_Year.Text.Replace(",", "").Replace(".", "")), Convert.ToInt32(txtDocument_Month.Text), Convert.ToInt32(txtDocument_Period.Text), _Type);

                //Xóa kỳ, chuyển kỳ hiện tại - 1
                //currPage = currPage > 0 ? currPage - 1 : 0;
                _DocumentID = BhHeader_Controller.Instance().Header_GetPreDocumentPeroid(Program.strBranchCode, Convert.ToInt32(txtDocument_Year.Text.Replace(",", "").Replace(".", "")), Convert.ToInt32(txtDocument_Month.Text), Convert.ToInt32(txtDocument_Period.Text), _Type);
                if (_DocumentID > 0)
                {
                    if (curPeriod > 1)
                        curPeriod -= 1;
                    else
                        curPeriod = 1;
                    txtDocument_Period.Text = curPeriod.ToString();
                }
                //
                arg_HeaderID = Header_GetList();
                Pager.Invalidate();
                //
                LoadList();
                txtDetail_Insbookno.Focus();
                MessageBox.Show("Đã xóa thành công dữ liệu của kỳ " + curPeriod.ToString() + " tháng " + txtDocument_Month.Text + " năm " + txtDocument_Year.Text.Replace(",", "").Replace(".", ""));
            }
        }

        private void btnForm03New_Click(object sender, EventArgs e)
        {
            if (_listRole.View)
            {
                frmPreviewReport f = new frmPreviewReport("BHXHMau03_KhongTangMoi", new string[] { "Mẫu 03", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", "") });
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //Khi nhập % vượt khung sẽ tính ra giá trị tương ứng
        private void txtOverFactor_Percent_Validated(object sender, EventArgs e)
        {
            if (txtDetail_Newoverfactor.Text.Length == 0)
                txtDetail_Newoverfactor.Text = "0";
            //
            decimal BasicFactor = UISetting.GetDecimalNo(txtDetail_Newbasicfactor.Text);
            decimal Percent_OverFactor = UISetting.GetDecimalNo(txtDetail_Newoverfactor_Percent.Text);
            txtDetail_Newoverfactor.Text = ((Percent_OverFactor * BasicFactor) / 100).ToString(UIParamater.Cham3So);
        }

        //Nhập % sẽ tính thâm niên nghề tương ứng
        private void txtJobFactor_Percent_Validated(object sender, EventArgs e)
        {
            decimal BasicFactor = UISetting.GetDecimalNo(txtDetail_Newbasicfactor.Text);
            decimal PositionFactor = UISetting.GetDecimalNo(txtDetail_Newpositionfactor.Text);
            decimal Percent_JobFactor = Globals.Object_GetValue<decimal>(txtDetail_Newjobfactor_Percent.Text);
            decimal OverFactor = UISetting.GetDecimalNo(txtDetail_Newoverfactor.Text);
            decimal JobFactor = (BasicFactor + PositionFactor + OverFactor) * Percent_JobFactor / 100;
            //
            txtDetail_Newoverfactor.Text = OverFactor.ToString(UIParamater.Cham3So);
            txtDetail_Newjobfactor.Text = JobFactor.ToString(UIParamater.Cham3So);
        }

        //
        protected string GetDecimalValueUtil(object obj, string Format)
        {
            if (obj == null || obj == DBNull.Value)
                return "";
            else
                return Convert.ToDecimal(obj).ToString(Format);
        }

        private void txtInsTypeCode_Validated(object sender, EventArgs e)
        {
            ThayDoiPhuongAn();
        }

        private void txtInsTypeCode_KeyUp(object sender, KeyEventArgs e)
        {
            //Nếu là enter thì không bắt
            if (e.KeyCode == Keys.Enter) return;
            if (txtDetail_Insbookno.Text.Length == 0) return;

            if (Globals.Object_GetValue<Int32>(dtInsTypeCode.Compute("COUNT(InsType_Code)", "InsType_Code LIKE '" + txtDetail_Instypecode.Text + "%'")) <= 0)
            {
                frmInsTypeList f = new frmInsTypeList(true);
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    txtDetail_Instypecode.Text = f.InsTypeCode;
                    txtDetail_Instypecode.SelectAll();
                    txtDetail_Instypecode.Focus();
                }
            }
            else if (txtDetail_Instypecode.Text.Trim().Length == 2 && txtDetail_Instypecode.SelectionLength != 2)
            {
                txtDetail_Socialrate.Focus();
            }
        }

        //Nhập % thâm niên vượt khung => lấy giá trị tương ứng
        private void txtOldOverFactor_Percent_Validated(object sender, EventArgs e)
        {
            if (txtDetail_Oldoverfactor.Text.Length == 0)
                txtDetail_Oldoverfactor.Text = "0";
            //
            decimal BasicFactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
            decimal Percent_OverFactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor_Percent.Text);
            txtDetail_Oldoverfactor.Text = ((Percent_OverFactor * BasicFactor) / 100).ToString(UIParamater.Cham3So);
        }

        //Nhập % thâm niên nghề mức cũ => fill dữ liệu tương ứng
        private void txtOldJobFactor_Percent_Validated(object sender, EventArgs e)
        {
            if (txtDetail_Oldjobfactor_Percent.Text.Length == 0)
                txtDetail_Oldjobfactor_Percent.Text = "0";
            //
            decimal BasicFactor = UISetting.GetDecimalNo(txtDetail_Oldbasicfactor.Text);
            decimal PositionFactor = UISetting.GetDecimalNo(txtDetail_Oldpositionfactor.Text);
            decimal Percent_JobFactor = UISetting.GetDecimalNo(txtDetail_Oldjobfactor_Percent.Text);
            decimal OverFactor = UISetting.GetDecimalNo(txtDetail_Oldoverfactor.Text);
            decimal JobFactor = (BasicFactor + PositionFactor + OverFactor) * Percent_JobFactor / 100;
            //
            txtDetail_Oldoverfactor.Text = OverFactor.ToString(UIParamater.Cham3So);
            txtDetail_Oldjobfactor.Text = JobFactor.ToString(UIParamater.Cham3So);
        }

        //Focus khỏi ô nhập mức lương mới => format số liệu
        private void txtNewAmount_Leave(object sender, EventArgs e)
        {
            if ((UISetting.GetDecimalNo(txtNewAmount.Text) > UISetting.GetDecimalNo(txtDocument_Basicsalary.Text) * 20) && UISetting.GetDecimalNo(txtDocument_Basicsalary.Text) > 0)
            {
                txtNewAmount.Text = (UISetting.GetDecimalNo(txtDocument_Basicsalary.Text) * 20).ToString("#,##0");
            }
        }

        private void disable_readonly()
        {
            FormGlobals.Control_SetViewOnly(false, txtDetail_Socialrate, txtDetail_Medicalrate, txtDetail_Unemployedrate);
            FormGlobals.Control_SetViewOnly(false, grbMucCu, grbMucMoi);
        }

        //-Click vào xem báo cáo
        private void Report_XemBaoCao(string sReportName)
        {
            if (!_listRole.View)
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
            {
                frmPreviewReport f = null;
                switch (sReportName)
                {
                    case "BHXHMau03_TEST":
                        f = new frmPreviewReport("BHXHMau03_TEST", new string[] { "Mẫu 03", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), _Type });
                        break;
                    case "BHXHMau03_KhongTangMoi_TEST":
                        f = new frmPreviewReport("BHXHMau03_KhongTangMoi_TEST", new string[] { "Mẫu 03", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), _Type });
                        break;
                    case "BHXH_Mau02aTBH_TEST":
                        f = new frmPreviewReport("BHXH_Mau02aTBH_TEST", new string[] { "Mẫu 02", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), "0", _Type });
                        break;
                    case "BHXHMauD02TS":
                        f = new frmPreviewReport("BHXHMauD02TS", new string[] { "Mẫu D02-TS", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), _Type });
                        break;
                    case "HSML_BHXHMauD02TS":
                        f = new frmPreviewReport("BHXHMauD02TS", new string[] { "Mẫu D02-TS", "0", txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), "" });
                        break;
                    case "BHXHMauD02TS_Moi":
                        f = new frmPreviewReport("BHXHMauD02TS_Moi", new string[] { "Mẫu D02-TS", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), _Type });
                        break;
                    case "HSML_BHXHMauD02TS_Moi":
                        f = new frmPreviewReport("BHXHMauD02TS_Moi", new string[] { "Mẫu D02-TS", "0", txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), "","" });
                        break;
                }
                //show report if it not is export excel/word/pdf
                if(!f.isExport)
                    f.Show(this);
            }
        }

        private void mẫu03aTBHTESTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("BHXHMau03_TEST");
        }

        private void mẫu03aTBHKhôngCóTMTESTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("BHXHMau03_KhongTangMoi_TEST");
        }

        private void mẫu02aTBHToànBộTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("BHXH_Mau02aTBH_TEST");
        }

        private void mẫuD02TSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("BHXHMauD02TS");
        }

        private void HSMLD02TSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("HSML_BHXHMauD02TS");
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("BHXHMauD02TS_Moi");
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Report_XemBaoCao("HSML_BHXHMauD02TS_Moi");
        }
        
        private void mẫuTờKhaiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_listRole.View)
            {
                frmToKhaiA01TS f = new frmToKhaiA01TS(dtQTBHTrongKy, _Type);
                f.ShowDialog(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //----------

        frmDieuChinhTheoNhom frm;
        private void điềuChỉnhTheoNhómToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frm = new frmDieuChinhTheoNhom(_listRole, Convert.ToInt32(txtDocument_Year.Text.Replace(",", "").Replace(".", "")), Convert.ToInt32(txtDocument_Month.Text), _Type);
            frm.WindowState = FormWindowState.Maximized;
            frm.saveTangLuongHangLoat += new frmDieuChinhTheoNhom.SaveTangLuongHangLoat(frm_saveTangLuongHangLoat);
            frm.ShowDialog(this);
        }

        //Tăng lương hàng loạt
        void frm_saveTangLuongHangLoat(DetailInfo detailInfo)
        {
            if (!SaveHeader())
            {
                UISetting.MesUpdateSuccesful();
                return;
            }
            //
            detailInfo.Detail_Id = 0;
            detailInfo.Detail_Documentid = _DocumentID;
            EmployeeInfo employeeInfo = _wcfEmployee.Employee_GetInfoBySIBookNo(detailInfo.Detail_Insbookno);
            detailInfo.Detail_Employeecode = employeeInfo.Code;
            detailInfo.Detail_Oldbasicfactor = detailInfo.Detail_Oldpositionfactor = detailInfo.Detail_Oldoverfactor = detailInfo.Detail_Oldjobfactor = detailInfo.Detail_Oldareafactor = detailInfo.Detail_Newbasicfactor = detailInfo.Detail_Newpositionfactor = detailInfo.Detail_Newoverfactor = detailInfo.Detail_Newjobfactor = detailInfo.Detail_Newareafactor = 0;
            detailInfo.Detail_Regioncode = !String.IsNullOrEmpty(employeeInfo.MedicalRegionCode) ? employeeInfo.MedicalRegionCode : Program.strRegionCode;
            detailInfo.Detail_Hospitalcode = _MedicalPlace;
            detailInfo.Detail_Status = 2;
            //detailInfo.TotalMonth = Convert.ToInt32(txtCount.Text);
            detailInfo.Detail_Description = "";
            detailInfo.Detail_Basicsalary = BasicSalary(detailInfo.Detail_Fromdate);
            //detailInfo.Description = txtChucDanh.Text.Trim();
            _DetailID = Detail_Controller.Instance().Detail_Insert(detailInfo);
            LoadList();
        }

        //Lọc danh sách phát sinh theo từ khóa
        private void btnFilter_Click(object sender, EventArgs e)
        {
            if (dgvList.DataSource != null)
            {
                string sFilter = txtKeyWord.Text.Trim() != "" ?
                    "Detail_InsBookNo like '%" + txtKeyWord.Text.Trim() + "%'"
                    + " OR Employee_FullName like '%" + txtKeyWord.Text.Trim() + "%'"
                    + " OR Detail_InsTypeCode = '" + txtKeyWord.Text.Trim() + "'"
                    : "";
                (dgvList.DataSource as DataTable).DefaultView.RowFilter = sFilter;
            }
        }

        //Các hàm dùng cho control pager
        private void PagerControl_PageChanged(int pageIndex)
        {
            try
            {
                FormGlobals.App_ProgressShow(new SubInvoker(Bind_Header), pageIndex, "");
                //
                Pager.PageIndex = pageIndex;
                //PagerControl.TotalRow = 
            }
            catch (Exception ex)
            {
                FormGlobals.Message_Error(ex);
            }
        }

        private void Bind_Header(object iPageIdx)
        {
            int idx = Globals.Object_GetValue<int>(iPageIdx);
            idx = idx >= 0 ? idx : 0;
            //
            if (_HeaderInfo.Document_Id > 0)
            {
                _DocumentID = arg_HeaderID[idx];
                _HeaderInfo = BhHeader_Controller.Instance().Header_GetInfo(_DocumentID);
                //
                HeaderInfo2Form();
                LoadList();
            }
        }

        //Các sự kiện xuất báo cáo
        private void btnForm02_Click(object sender, EventArgs e)
        {
            if (_listRole.View)
            {
                frmPreviewReport f = new frmPreviewReport("BHXH_Mau02aTBH", new string[] { "Mẫu 02", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), "0" });
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnForm02All_Click(object sender, EventArgs e)
        {
            if (_listRole.View)
            {
                frmPreviewReport f = new frmPreviewReport("BHXH_Mau02aTBH", new string[] { "Mẫu 02 toàn Cty", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", ""), "1" });
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnForm03_Click(object sender, EventArgs e)
        {
            if (_listRole.View)
            {
                frmPreviewReport f = new frmPreviewReport("BHXHMau03", new string[] { "Mẫu 03", txtDocument_Period.Text, txtDocument_Month.Text, txtDocument_Year.Text.Replace(",", "").Replace(".", "") });
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //Hứng sự kiện enter để nhấn nút
        private void tsToolbar_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (btnSave.Selected)
                    btnSave.PerformClick();
                else if (btnNewDocument.Selected)
                    btnNewDocument.PerformClick();
            }
        }

        private void frmInsurance_Load(object sender, EventArgs e)
        {
            //TextBox_SetTransparentLabel(lblOldVK_Per, txtDetail_Oldoverfactor_Percent);
            //TextBox_SetTransparentLabel(lblOldNghe_Per, txtDetail_Oldjobfactor_Percent);
            //TextBox_SetTransparentLabel(lblNewVK_Per, txtDetail_Newoverfactor_Percent);
            //TextBox_SetTransparentLabel(lblNewNghe_Per, txtDetail_Newjobfactor_Percent);
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnFilter_Click(null, null);
            }
        }

        private void txtKeyWord_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnFilter_Click(null, null);
            }
        }
    }
}
